2011-06-24 60 views
5

Tôi đang tạo một ứng dụng có hình ảnh từ máy ảnh và sau đó gửi nó qua email.Nén hình ảnh trong android

Bạn bè vì bạn biết rằng hình ảnh từ máy ảnh có thể có độ phân giải quá nhiều và cũng có kích thước, ví dụ: 2.0MB và nhiều hơn nữa vì vậy những gì tôi muốn là để tái kích thước hình ảnh trong kích thước cũng như độ phân giải để tôi có thể đính kèm tập tin đó vào email.

Vì vậy, bất kỳ ai cũng có thể cho tôi một số mẫu mã hoặc một số nguyên tắc để vượt qua vấn đề của tôi.

Cảm ơn trước

Trả lời

5

bạn có thể làm điều này để nén bitmap ..

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

vì vậy điều này sẽ tạo bitmap theo kích thước yêu cầu của tôi và sau đó lưu trữ trong đối tượng Bitmap của tôi ??? – Shah

+0

@sujit Cảm ơn vì mã yên bình nhưng nó làm cho kích thước ngắn nhưng không kích thước. Bạn có thể cho tôi biết cách duy trì tỷ lệ khung hình không? – Creator

4

thử ví dụ này

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

bạn có thể thử điều này cũng

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

Để thay đổi kích thước hình ảnh thử với các fol mã lowing

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

Hãy thử điều này. Tôi nghĩ đây là ví dụ nén hình ảnh phù hợp nhất cho đến bây giờ.

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

Các liên kết bên ngoài thường xuyên bị chết và mọi câu trả lời phụ thuộc rất nhiều vào các liên kết bên ngoài trở nên vô dụng trong một sự kiện như vậy. Do đó, vui lòng bao gồm mã có liên quan trong nội dung mã. –

Các vấn đề liên quan