Android 使用activitytresult调整图像大小
如何使用下面的代码调整图像大小?代码得到图像,但我不知道如何调整它的大小Android 使用activitytresult调整图像大小,android,Android,如何使用下面的代码调整图像大小?代码得到图像,但我不知道如何调整它的大小 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
//file name
filePath = data.getData();
try {
// Bundle extras2 = data.getExtras();
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// imageview.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("image", imageInByte);
startActivity(i);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我用这种方式读了一本书,但它和我的方式不同
File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Bitmap b= BitmapFactory.decodeFile(PATH_ORIGINAL_IMAGE);
Bitmap out = Bitmap.createScaledBitmap(b, 320, 480, false);
File file = new File(dir, "resize.png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
} catch (Exception e) {}
我建议您首先将位图图像设置为imageview并应用缩放,即使用setScaleType方法根据您的要求调整大小 例: imageview.setScaleType(ScaleType.CENTER) (或) 如果你想以同样的方式尝试,那么我认为这个链接可能会有帮助
要告诉解码器对图像进行二次采样,将较小的版本加载到内存中,请在BitmapFactory.Options对象中将inSampleSize设置为true。例如,分辨率为2048x1536的图像在inSampleSize为4的情况下解码后生成约为512x384的位图。将其加载到内存时,整个图像使用0.75MB而不是12MB(假设位图配置为ARGB_8888)。以下是一种基于目标宽度和高度计算样本大小值的方法,该值是2的幂:
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;
}
摘自谢谢您的回答,我正在从sd卡(如上所示)中获取图像,然后将其作为意图发送到另一个活动,并在图像视图中进行设置。那么你是说在图像视图中设置它之后,然后调整它的大小?谢谢你的asnwer,所以这个会减小图像的大小,对吗?我的图像大小约为200kb,我想将其设置为50kb,它不会影响图像质量、纵横比或memroy泄漏?不会,它会降低图像分辨率并间接降低图像大小,如果您想降低文件大小而不是图像分辨率,请将其转换为JPEG,如果您的imageview分辨率低于图像分辨率,则应使用insamplesize降低分辨率,这样您就不会将整个图像加载到内存中,而是将其jpg的大小缩小,如果保存,这是照片的最大尺寸,你会注意到它的200kb,我想让它大约50kb或更少,但质量保持不变。