此範例作用為圖片翻轉會產生out of memory問題, 藉由inSampleSize去調整縮放比例則可以解決此問題

 

package com.example.photoRatation;

import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {

/*  this comment use for test  */  
 public ImageView imageView1;
 int deg = 0;
 @SuppressLint("SdCardPath")
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  Runtime rt = Runtime.getRuntime();
  long maxMemory = rt.maxMemory();
  Log.d("00000000000", "maxMemory:" + Long.toString(maxMemory));
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageView1 = (ImageView) findViewById(R.id.imageView1);
  String sourceFilePath = "file:///mnt/sdcard/DCIM/100MEDIA/IMAG0005.jpg";
  String newFilePath = "file:///mnt/sdcard/DCIM/100MEDIA/";
  photoRotation(sourceFilePath, newFilePath, deg);
 }

 public String photoRotation(String sourceFilePath, String newFilePath, int deg) {
  try {
   if (sourceFilePath == null) {
    return null;
   }
   Uri uri = Uri.parse(sourceFilePath);
   ContentResolver cr = this.getContentResolver();
   deg = deg - 90;
   
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPreferredConfig = android.graphics.Bitmap.Config.RGB_565;
   options.outHeight = 1840; 
   options.outWidth = 3264;  
   options.inSampleSize = calculateInSampleSize(options, 32, 64);
   
   
   Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
   Matrix m = new Matrix();
   int width = bitmap.getWidth();
   int height = bitmap.getHeight();
   m.setRotate(deg);
   Bitmap bmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
   //imageView1.setImageBitmap(bmap);
   
   newFilePath = bmap.toString();
      //return newFilePath;
   
  } catch (OutOfMemoryError ooe) {
   ooe.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return newFilePath;
 }
 
 public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
  // Raw height and width of image
  final int height = options.outHeight;
  final int width = options.outWidth;
  int inSampleSize = 1;

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

arrow
arrow

    Will 發表在 痞客邦 留言(0) 人氣()