如何在用android上传图片之前进行压缩图片?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (49)

我正在通过我的应用程序上传一些图像,一些图像因为它们的大小无法上传...如何解决这个问题?请帮忙

 if (requestCode == pickImageCode && resultCode == Activity.RESULT_OK && data != null) {

            table = data.data
            val arrayOfData = arrayOf(MediaStore.Images.Media.DATA)
            val myImageQuery = view!!.context.contentResolver.query(table, arrayOfData, null, null, null)
            myImageQuery.moveToFirst()
            val columnIndex = myImageQuery.getColumnIndex(arrayOfData[0])
            imagePath = myImageQuery.getString(columnIndex)
            myImageQuery.close()
            val myImage = BitmapFactory.decodeFile(imagePath)
            imageToInSendLayout.setImageBitmap(myImage)


        } else {
            return
        }

        imageUri = data.data

在发送到服务器之前将图像预览到imageView

提问于
用户回答回答于

您可以使用lib Picasso:

Picasso
    .with(context)
    .load(path)
    .resize(sizeW, sizeH)
    .centerCrop()
    .into(target)
用户回答回答于

您可以做的是(Java版本,我在任何地方都没有Kotlin版本:):

BitmapFactory.Options bounds = new BitmapFactory.Options();
        bounds.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, bounds);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = calculateInSampleSize(bounds, reqWidth, reqHeight);
        Bitmap bm = BitmapFactory.decodeFile(imagePath, opts);

where

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int inSampleSize = 1;
        if (reqWidth != 0 & reqHeight != 0) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;

            if (height > reqHeight || width > reqWidth) {

                final int halfHeight = height / 2;
                final int halfWidth = width / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) >= reqHeight
                        && (halfWidth / inSampleSize) >= reqWidth) {
                    inSampleSize *= 2;
                }
            }
        }
        return inSampleSize;
    }

所发生的是:您解码文件数据,然后,通过传递reqWidth/reqHigh,使其变得更小。然后您可以将其传递到您的布局:)

扫码关注云+社区

领取腾讯云代金券