【问题标题】:Android, how to reduce the size of a bitmap?Android,如何减小位图的大小?
【发布时间】:2019-04-16 10:57:51
【问题描述】:

我有一个应用程序允许用户将他们的个人资料图像更改为存储在他们设备上的另一个图像。为此,应用程序将选定的图像发送到远程服务器。这一切都很好,所以我不放那部分的代码,以免使问题复杂化。我的问题是我希望减小发送到服务器的位图的大小,以防止例如 5 或 6 兆字节的大文件,这会降低应用程序的速度。但结局并不好。

这是我的代码:

if (requestCode == 1 && resultCode == RESULT_OK) {

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);

            ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();

            //Resize the bitmap
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, false);

            resizedBitmap.compress(Bitmap.CompressFormat.JPEG,50,bytearrayoutputstream);


            //Round the image
            int min = Math.min(resizedBitmap.getWidth(), resizedBitmap.getHeight());

            Bitmap bitmapRounded = Bitmap.createBitmap(min, min, resizedBitmap.getConfig());

            Canvas canvas = new Canvas(bitmapRounded);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setShader(new BitmapShader(resizedBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
            canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min / 2, min / 2, paint);

            //bitmap to imageView
            avatar.setImageBitmap(bitmapRounded);

}

我试图缩小它的大小(它不起作用),然后在将其调整到相应的 ImageView 之前对图像进行四舍五入(这很好)。

唯一不能让它正常工作的就是减小位图的大小。

【问题讨论】:

    标签: android bitmap


    【解决方案1】:

    我正在使用它来减小我的位图大小并且它工作正常:-

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
    

    【讨论】:

      【解决方案2】:

      如果你想让你的图像更小,你需要先得到你的位图的高度和宽度,计算比例然后可以创建一个缩放的位图。

      int width = image.getWidth();
      int height = image.getHeight();
      

      您必须计算图像大小并返回缩放的位图。

      在这里找到类似的问题:Reduce the size of a bitmap to a specified size in Android

      希望你能得到确切的解决方案。

      【讨论】:

        【解决方案3】:

        试试这个:

        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, ostream);
        

        【讨论】:

        • 不幸的是,这个解决方案存在一些限制。如果源是 PNG 文件,它根本不做任何事情。此外,如果 CompressFormat 设置为 PNG,则压缩不会对位图做任何事情
        【解决方案4】:

        我正在使用这个助手类。

        public class ScaleFile {
            private Context mContext;
        
            public ScaleFile(Context context) {
                this.mContext = context;
            }
        
            public Bitmap scaleFile(String imageUri) {
        
                String filePath = getRealPathFromURI(imageUri);
                Bitmap scaledBitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
        
        
                options.inJustDecodeBounds = true;
                Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
        
                int actualHeight = options.outHeight;
                int actualWidth = options.outWidth;
        
                 //max Height and width values of the compressed image is taken as 816x612
        
                float maxHeight = 816.0f;
                float maxWidth = 612.0f;
                float imgRatio = actualWidth / actualHeight;
                float maxRatio = maxWidth / maxHeight;
        
                //width and height values are set maintaining the aspect ratio of the image
        
                if (actualHeight > maxHeight || actualWidth > maxWidth) {
                    if (imgRatio < maxRatio) {
                        imgRatio = maxHeight / actualHeight;
                        actualWidth = (int) (imgRatio * actualWidth);
                        actualHeight = (int) maxHeight;
                    } else if (imgRatio > maxRatio) {
                        imgRatio = maxWidth / actualWidth;
                        actualHeight = (int) (imgRatio * actualHeight);
                        actualWidth = (int) maxWidth;
                    } else {
                        actualHeight = (int) maxHeight;
                        actualWidth = (int) maxWidth;
        
                    }
                }
        
            //setting inSampleSize value allows to load a scaled down version of the original image
        
                options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
        
        
                options.inPurgeable = true;
                options.inInputShareable = true;
                options.inTempStorage = new byte[16 * 1024];
        
                try {
                    //load the bitmap from its path
                    bmp = BitmapFactory.decodeFile(filePath, options);
                } catch (OutOfMemoryError exception) {
                    exception.printStackTrace();
        
                }
                try {
                    scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
                } catch (OutOfMemoryError exception) {
                    exception.printStackTrace();
                }
        
                float ratioX = actualWidth / (float) options.outWidth;
                float ratioY = actualHeight / (float) options.outHeight;
                float middleX = actualWidth / 2.0f;
                float middleY = actualHeight / 2.0f;
        
                Matrix scaleMatrix = new Matrix();
                scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
        
                Canvas canvas = new Canvas(scaledBitmap);
                canvas.setMatrix(scaleMatrix);
                canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
        
                 // check the rotation of the image and display it properly
                ExifInterface exif;
                try {
                    exif = new ExifInterface(filePath);
        
                    int orientation = exif.getAttributeInt(
                            ExifInterface.TAG_ORIENTATION, 0);
                    Matrix matrix = new Matrix();
                    if (orientation == 6) {
                        matrix.postRotate(90);
                    } else if (orientation == 3) {
                        matrix.postRotate(180);
                    } else if (orientation == 8) {
                        matrix.postRotate(270);
                    }
                    scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                            scaledBitmap.getHeight(), matrix, true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
                return scaledBitmap;
            }
        
            private String getRealPathFromURI(String contentURI) {
                Uri contentUri = Uri.parse(contentURI);
                Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
                if (cursor == null) {
                    return contentUri.getPath();
                } else {
                    cursor.moveToFirst();
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    return cursor.getString(index);
                }
            }
        
            public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
                final int height = options.outHeight;
                final int width = options.outWidth;
                int inSampleSize = 1;
        
                if (height > reqHeight || width > reqWidth) {
                    final int heightRatio = Math.round((float) height / (float) reqHeight);
                    final int widthRatio = Math.round((float) width / (float) reqWidth);
                    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
                }
                final float totalPixels = width * height;
                final float totalReqPixelsCap = reqWidth * reqHeight * 2;
                while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                    inSampleSize++;
                }
        
                return inSampleSize;
            }
        
        }
        

        【讨论】:

          【解决方案5】:

          这是对你有用的代码。

          /**
           * reduces the size of the image
           * @param image
           * @param maxSize
           * @return
           */
          public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
              int width = image.getWidth();
              int height = image.getHeight();
          
              float bitmapRatio = (float)width / (float) height;
              if (bitmapRatio > 1) {
                  width = maxSize;
                  height = (int) (width / bitmapRatio);
              } else {
                  height = maxSize;
                  width = (int) (height * bitmapRatio);
              }
              return Bitmap.createScaledBitmap(image, width, height, true);
          }
          
          Bitmap converetdImage = getResizedBitmap(selectedImageUri, 500);
          

          您可以从以下 URL 参考它。 Reduce the size of a bitmap to a specified size in Android

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-06-01
            • 1970-01-01
            • 2013-11-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多