将旋转的位图保存到SD卡后图像质量不佳

时间:2013-12-20 04:48:20

标签: android

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

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();

        }
    });

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

1 个答案:

答案 0 :(得分:2)

尝试以下代码以减少图像尺寸而不会降低其质量:

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

<强>编辑:

使用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);
相关问题