将旋转位图保存到 SD 卡后图像质量较差

问题描述 投票:0回答:1

我正在制作一个应用程序,在其中一个活动中我从图库中获取图像并将其显示在适配器中,如下图所示

enter image description here

我必须旋转该图像并将其保存到 SD 卡。我的代码运行良好,但将其保存到 SD 卡后,图像质量非常差。我的代码是:

 viewHolder.imgViewRotate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            imagePosition = (Integer) v.getTag();
            Matrix matrix = new Matrix();
            matrix.postRotate(90);

            Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            try {
                FileOutputStream out = new FileOutputStream(new File(uriList.get(rotatePosition).toString()));
                rotated.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            notifyDataSetChanged();

        }
    });

任何建议都会有很大帮助。

android
1个回答
2
投票

使用

BitmapFactory
inSampleSize
选项调整图像大小,图像根本不会损失质量。代码:

          BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
              bmpFactoryOptions.inJustDecodeBounds = true;
              Bitmap bm = BitmapFactory.decodeFile(tempDir+"/"+photo1_path , bmpFactoryOptions);

              int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)600);
              int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)800);

              if (heightRatio > 1 || widthRatio > 1)
              {
               if (heightRatio > widthRatio){
                bmpFactoryOptions.inSampleSize = heightRatio;
               } else {
                bmpFactoryOptions.inSampleSize = widthRatio; 
               } 
              }

              bmpFactoryOptions.inJustDecodeBounds = false;
              bm = BitmapFactory.decodeFile(tempDir+"/"+photo1_path, bmpFactoryOptions);
             
              // recreate the new Bitmap
        src = Bitmap.createBitmap(bm, 0, 0,bm.getWidth(), bm.getHeight(), matrix, true);
        src.compress(Bitmap.CompressFormat.PNG, 100, out);
© www.soinside.com 2019 - 2024. All rights reserved.