如何在使用 android 上传之前压缩图像?

How to copress image before uploading with android?

我正在通过我的应用程序上传一些图片,有些图片由于尺寸原因无法上传...如何解决? 请帮助

 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

您可以使用 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);

哪里

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/reqheight 使其变小。然后你可以将它传递给你的布局:)