gpt4 book ai didi

android - 如何以编程方式压缩图像

转载 作者:行者123 更新时间:2023-11-29 16:23:32 36 4
gpt4 key购买 nike

我的资源文件夹中有 30 到 40 张图片。我目前正在使用 DrawBitpMap() 在我的屏幕上绘制它。但它给了我一个错误“VM outOfMemeory 错误”。所以我试着调整图像的大小。现在我的图像分辨率是 160x160。现在我没有得到那个错误。它运行没有任何问题。所以我的问题是,无论如何,我可以通过编程方式压缩我的图像,而不是手动调整资源中图像的大小吗?

最佳答案

尝试使用这个例子

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

你也可以这样做

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

关于android - 如何以编程方式压缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5932666/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com