100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > android图片上传大小限制 Android解决图片上传过大问题

android图片上传大小限制 Android解决图片上传过大问题

时间:2020-08-13 03:19:44

相关推荐

android图片上传大小限制 Android解决图片上传过大问题

最近在实现一个多图上传的功能(以流的形式上传),发现当上传图片超过5张的时候,就会报内存溢出的问题,去相册查看了一下,原来现在每张照片都占到2,3mb,如果几张大图就这么直接加载到内存中,肯定会溢出的,因此必须对图片进行处理。经过一

番查找和研究,终于找到了一个比较合适的方法去处理:

public static byte[] getSmallBitmapToBaos(String filePath) {

byte[] buffer = null;

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

options.inJustDecodeBounds = true;

BitmapFactory.decodeFile(filePath, options);

// Calculate inSampleSize

options.inSampleSize = calculateInSampleSize(options, 480, 800);

// Decode bitmap with inSampleSize set

options.inJustDecodeBounds = false;

Bitmap bm = BitmapFactory.decodeFile(filePath, options);

if(bm == null){

return null;

}

int degree = readPictureDegree(filePath);

bm = rotateBitmap(bm,degree) ;

ByteArrayOutputStream baos = null ;

try{

baos = new ByteArrayOutputStream();

press(pressFormat.JPEG, 30, baos);

buffer = baos.toByteArray();

}finally{

try {

if(baos != null)

baos.close() ;

} catch (IOException e) {

e.printStackTrace();

}

}

return buffer ;

}

private 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) {

// Calculate ratios of height and width to requested height and

// width

final int heightRatio = Math.round((float) height

/ (float) reqHeight);

final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will

// guarantee

// a final image with both dimensions larger than or equal to the

// requested height and width.

inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;

}

return inSampleSize;

}

private static int readPictureDegree(String path) {

int degree = 0;

try {

ExifInterface exifInterface = new ExifInterface(path);

int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

switch (orientation) {

case ExifInterface.ORIENTATION_ROTATE_90:

degree = 90;

break;

case ExifInterface.ORIENTATION_ROTATE_180:

degree = 180;

break;

case ExifInterface.ORIENTATION_ROTATE_270:

degree = 270;

break;

}

} catch (IOException e) {

e.printStackTrace();

}

return degree;

}

private static Bitmap rotateBitmap(Bitmap bitmap, int rotate){

if(bitmap == null)

return null ;

int w = bitmap.getWidth();

int h = bitmap.getHeight();

// Setting post rotate to 90

Matrix mtx = new Matrix();

mtx.postRotate(rotate);

return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。