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

标签 android image

我的资源文件夹中有 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/

相关文章:

javascript - 我的 JavaScript 图片库 slider 的右侧 slider 无法正常工作,而左侧的 slider 可以正常工作

c++ - 使用 Pleora SDK 保存缓冲区会得到蓝色、双倍的 BMP,下方有灰色条

Python将png文件发送到默认打印机

android - 如何以编程方式锁定展开/折叠 Action ?

android - 9 补丁图像在错误的位置缩放

java - 将映射值转换为字符串数组

java - 数组 = 列表<数组> .get(int) : Program crashes

c++ - C++中圆形区域中的Opencv对象检测

android - Eclipse 如何向现有的 Android 项目添加小部件

android - 一项 Activity 中的两个微调器