您的位置:首页 > 移动开发 > Android开发

Android 图像缩略图及压缩图像

2014-04-13 13:05 363 查看
    Android可以通过调用系统摄像头来获取图像,由于拍照的图像太大会造成java.lang.OutOfMemoryError错误。为了避免这种情况发生,可以通过缩略图的方式来分配更少的内存,即以牺牲图像的质量为代价。

    缩略图主要通过BitmapFactory.Options来实现。

    如果该值设为true,那么将不返回实际的bitmap,也不给其分配内存空间,这样就避免内存溢出。当允许读取图像的信息如图像大小。

    BitmapFactory.Options options;

    options.outHeight  图像原始高度

    options.outWidth   图像原始宽度

    通过options.inSampleSize来实现缩放。

     如果值设置为>1,要求解码器解码出原始图像的一个子样本,返回一个较小的bitmap,以节省存储空间。

    例如,inSampleSize == 2,则取出的缩略图的宽和高都是原始图像的1/2,图像的大小为原始图像的1/4。对于任何值<=1的同样处置为1。这里要注意的是,inSampleSize可能小于0,必须做判断。

    具体步骤如下:

    1、通过调用系统摄像头获取图像

String photoPath;
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String path = Environment.getExternalStorageDirectory().getPath()+ "/";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String photoName = formatter.format(new Date()) + ".jpg";
photoPath = path + photoName;
Uri uri = Uri.fromFile(new File(path, photoName));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, requestCode);

    2、如果为竖屏拍照,需要对图像进行旋转处理

private int getRotationForImage(String path) {
int rotation = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotation = 270;
break;
default:
rotation = 0;
}
} catch (IOException e) {
e.printStackTrace();
}
return rotation;
}
public static Bitmap rotaingBitmap(int angle , Bitmap bitmap) {
//旋转图片动作
Matrix matrix = new Matrix();;
matrix.postRotate(angle);
//创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
    3、压缩并保持图像

public void saveCompress(Bitmap bitmap, String filepath) {
File file = new File(filepath);
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out)) { //40是压缩率,表示压缩60%,如果不压缩为100,表示压缩率为0

out.flush();
out.close();
}
}catch (Exception e) {

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐