2011-06-24 178 views
5

我正在製作一個應用程序,它從相機拍攝圖像,然後通過電子郵件發送。在android中壓縮圖像

朋友,因爲您知道相機中的圖像可能分辨率太高,尺寸也很大,例如, 2.0MB和更多,所以我想要的是重新調整大小和分辨率的圖像大小,以便我可以將該文件附加到電子郵件。

所以,任何人都可以給我一些代碼示例或一些指導方針來解決我的問題。

在此先感謝

回答

5

你可以做到這一點壓縮的BitMap ..

mBitmap = Bitmap.createScaledBitmap(mBitmap, 160, 160, true); 
+0

兄弟,所以這將創建我所需的大小的位圖,然後存儲在我的位圖對象? – Shah

+0

@sujit感謝和平代碼,但它使尺寸短但不是尺寸。你能告訴我如何保持寬高比嗎? – Creator

4

嘗試這個例子

public class bitmaptest extends Activity { 
@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    LinearLayout linLayout = new LinearLayout(this); 

    // load the origial BitMap (500 x 500 px) 
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
      R.drawable.android); 

    int width = bitmapOrg.width(); 
    int height = bitmapOrg.height(); 
    int newWidth = 200; 
    int newHeight = 200; 

    // calculate the scale - in this case = 0.4f 
    float scaleWidth = ((float) newWidth)/width; 
    float scaleHeight = ((float) newHeight)/height; 

    // createa matrix for the manipulation 
    Matrix matrix = new Matrix(); 
    // resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 
    // rotate the Bitmap 
    matrix.postRotate(45); 

    // recreate the new Bitmap 
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
         width, height, matrix, true); 

    // make a Drawable from Bitmap to allow to set the BitMap 
    // to the ImageView, ImageButton or what ever 
    BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); 

    ImageView imageView = new ImageView(this); 

    // set the Drawable on the ImageView 
    imageView.setImageDrawable(bmd); 

    // center the Image 
    imageView.setScaleType(ScaleType.CENTER); 

    // add ImageView to the Layout 
    linLayout.addView(imageView, 
     new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT 
      ) 
    ); 

    // set LinearLayout as ContentView 
    setContentView(linLayout); 
} 
} 

你可以試試這個也

Bitmap.createScaledBitmap(yourimage, 160, 160, true); 
3

要調整圖像嘗試與fol降低代碼

public static Bitmap resizeBitMapImage1(String filePath, int targetWidth, 
      int targetHeight) { 
     Bitmap bitMapImage = null; 
     // First, get the dimensions of the image 
     Options options = new Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(filePath, options); 
     double sampleSize = 0; 
     // Only scale if we need to 
     // (16384 buffer for img processing) 
     Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math 
       .abs(options.outWidth - targetWidth); 

     if (options.outHeight * options.outWidth * 2 >= 1638) { 
      // Load, scaling to smallest power of 2 that'll get it <= desired 
      // dimensions 
      sampleSize = scaleByHeight ? options.outHeight/targetHeight 
        : options.outWidth/targetWidth; 
      sampleSize = (int) Math.pow(2d, 
        Math.floor(Math.log(sampleSize)/Math.log(2d))); 
     } 

     // Do the actual decoding 
     options.inJustDecodeBounds = false; 
     options.inTempStorage = new byte[128]; 
     while (true) { 
      try { 
       options.inSampleSize = (int) sampleSize; 
       bitMapImage = BitmapFactory.decodeFile(filePath, options); 

       break; 
      } catch (Exception ex) { 
       try { 
        sampleSize = sampleSize * 2; 
       } catch (Exception ex1) { 

       } 
      } 
     } 

     return bitMapImage; 
    } 
1

試試這個。我認爲這是一個最適合圖像壓縮的例子。

public String compressImage(String imageUri) { 
    String filePath = getRealPathFromURI(imageUri); 
     Bitmap scaledBitmap = null; 

     BitmapFactory.Options options = new BitmapFactory.Options(); 

//  by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If 
//  you try the use the bitmap here, you will get null. 
     options.inJustDecodeBounds = true; 
     Bitmap bmp = BitmapFactory.decodeFile(filePath, options); 

     int actualHeight = options.outHeight; 
     int actualWidth = options.outWidth; 

//  max Height and width values of the compressed image is taken as 816x612 

     float maxHeight = 816.0f; 
     float maxWidth = 612.0f; 
     float imgRatio = actualWidth/actualHeight; 
     float maxRatio = maxWidth/maxHeight; 

//  width and height values are set maintaining the aspect ratio of the image 

     if (actualHeight > maxHeight || actualWidth > maxWidth) { 
      if (imgRatio < maxRatio) {    imgRatio = maxHeight/actualHeight;    actualWidth = (int) (imgRatio * actualWidth);    actualHeight = (int) maxHeight;    } else if (imgRatio > maxRatio) { 
       imgRatio = maxWidth/actualWidth; 
       actualHeight = (int) (imgRatio * actualHeight); 
       actualWidth = (int) maxWidth; 
      } else { 
       actualHeight = (int) maxHeight; 
       actualWidth = (int) maxWidth; 

      } 
     } 

//  setting inSampleSize value allows to load a scaled down version of the original image 

     options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight); 

//  inJustDecodeBounds set to false to load the actual bitmap 
     options.inJustDecodeBounds = false; 

//  this options allow android to claim the bitmap memory if it runs low on memory 
     options.inPurgeable = true; 
     options.inInputShareable = true; 
     options.inTempStorage = new byte[16 * 1024]; 

     try { 
//   load the bitmap from its path 
      bmp = BitmapFactory.decodeFile(filePath, options); 
     } catch (OutOfMemoryError exception) { 
      exception.printStackTrace(); 

     } 
     try { 
      scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888); 
     } catch (OutOfMemoryError exception) { 
      exception.printStackTrace(); 
     } 

     float ratioX = actualWidth/(float) options.outWidth; 
     float ratioY = actualHeight/(float) options.outHeight; 
     float middleX = actualWidth/2.0f; 
     float middleY = actualHeight/2.0f; 

     Matrix scaleMatrix = new Matrix(); 
     scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); 

     Canvas canvas = new Canvas(scaledBitmap); 
     canvas.setMatrix(scaleMatrix); 
     canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight()/2, new Paint(Paint.FILTER_BITMAP_FLAG)); 

//  check the rotation of the image and display it properly 
     ExifInterface exif; 
     try { 
      exif = new ExifInterface(filePath); 

      int orientation = exif.getAttributeInt(
        ExifInterface.TAG_ORIENTATION, 0); 
      Log.d("EXIF", "Exif: " + orientation); 
      Matrix matrix = new Matrix(); 
      if (orientation == 6) { 
       matrix.postRotate(90); 
       Log.d("EXIF", "Exif: " + orientation); 
      } else if (orientation == 3) { 
       matrix.postRotate(180); 
       Log.d("EXIF", "Exif: " + orientation); 
      } else if (orientation == 8) { 
       matrix.postRotate(270); 
       Log.d("EXIF", "Exif: " + orientation); 
      } 
      scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, 
        scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, 
        true); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     FileOutputStream out = null; 
     String filename = getFilename(); 
     try { 
      out = new FileOutputStream(filename); 

//   write the compressed bitmap at the destination specified by filename. 
      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     return filename; 
    } 
private String getRealPathFromURI(String contentURI) { 
     Uri contentUri = Uri.parse(contentURI); 
     Cursor cursor = getContentResolver().query(contentUri, null, null, null, null); 
     if (cursor == null) { 
      return contentUri.getPath(); 
     } else { 
      cursor.moveToFirst(); 
      int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
      return cursor.getString(index); 
     } 
    } 


public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 
     final int heightRatio = Math.round((float) height/ (float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;  }  final float totalPixels = width * height;  final float totalReqPixelsCap = reqWidth * reqHeight * 2;  while (totalPixels/(inSampleSize * inSampleSize) > totalReqPixelsCap) { 
     inSampleSize++; 
    } 

    return inSampleSize; 
} 
+1

外部鏈接經常死亡,任何嚴重依賴外部鏈接的答案在這樣的事件中變得毫無用處。因此,請在代碼正文中包含相關代碼。 –