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

时间:2019-06-11 17:28:10

标签: android image kotlin bitmap

我正在通过我的应用程序上载一些图像,某些图像由于尺寸而无法上载...如何解决呢? 请帮助

 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中

2 个答案:

答案 0 :(得分:0)

您能做的是(对不起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来使其更小。然后,您可以将其传递给您的布局:)

答案 1 :(得分:-1)

您可以使用lib Picasso:

    String S = "";
    Scanner sc = new Scanner(System.in);
    int D = sc.nextInt();
    for(int i=0;i<D;i++) {
         S = S + sc.next();
    }
    System.out.println(S);