`
jk138
  • 浏览: 150355 次
  • 性别: Icon_minigender_1
  • 来自: 茂名
社区版块
存档分类
最新评论

缩放图片的方法

 
阅读更多

代码一:

 

public Bitmap ResizeBitmap(Bitmap bitmap, int newWidth) { 
            int width = bitmap.getWidth(); 
            int height = bitmap.getHeight(); 
            float temp = ((float) height) / ((float) width); 
            int newHeight = (int) ((newWidth) * temp); 
            float scaleWidth = ((float) newWidth) / width; 
            float scaleHeight = ((float) newHeight) / height; 
            Matrix matrix = new Matrix(); 
            // resize the bit map 
            matrix.postScale(scaleWidth, scaleHeight); 
            // matrix.postRotate(45); 
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); 
            bitmap.recycle(); 
            return resizedBitmap; 
       }    

 代码二:

   public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {

            int originWidth  = bitmap.getWidth();
            int originHeight = bitmap.getHeight();

            // no need to resize
            if (originWidth < maxWidth && originHeight < maxHeight) {
                return bitmap;
            }

            int width  = originWidth;
            int height = originHeight;

            // 若图片过宽, 则保持长宽比缩放图片
            if (originWidth > maxWidth) {
                width = maxWidth;

                double i = originWidth * 1.0 / maxWidth;
                height = (int) Math.floor(originHeight / i);

                bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
            }

            // 若图片过长, 则从上端截取
            if (height > maxHeight) {
                height = maxHeight;
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
            }

//            Log.i(TAG, width + " width");
//            Log.i(TAG, height + " height");
              
            return bitmap;
        }
        
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics