如何在安卓系统中将位图设置为ARGB_8888格式?

4
在我的Android项目中,我从手机上的图像加载了一个位图。然后,我对它进行各种图像操作,例如裁剪、调整大小和编辑像素值。
但问题在于,该位图的格式不是ARGB_8888,因此它实际上并没有存储alpha值。或者说它始终将alpha值保持为255。
那么我该如何在ARGB_8888格式下加载位图呢?下面是我的加载和调整大小代码,请问我应该在哪里指定格式?
谢谢。
private static Bitmap resize(Bitmap img, int newW, int newH) throws IOException {
    Bitmap resizedImg = Bitmap.createScaledBitmap(img, newW, newH, false);
    img.recycle();

    Bitmap newresizedImg = resizedImg.copy(Bitmap.Config.ARGB_8888, true);
    resizedImg.recycle();


    Pixel initialPixel = Function.getPixel(0, 0, newresizedImg, null);
    int a = initialPixel.getColor().getAlpha(); // -> 255
    newresizedImg.setPixel(0, 0, Pixel.getTransparentColor().getRGB());
    initialPixel = Function.getPixel(0, 0, newresizedImg, null);
    int new_a = initialPixel.getColor().getAlpha(); // -> 255

    return newresizedImg;
}

private static Bitmap getImage(String from) throws IOException {
    File file = new File(from);

    if (file.exists()) {
        BitmapFactory.Options op = new BitmapFactory.Options(); 
        op.inPreferredConfig = Bitmap.Config.ARGB_8888; 
        Bitmap bufferedImage = BitmapFactory.decodeFile(from, op);
        return bufferedImage;
    }
    return null;
}

像素类
public static Color getTransparentColor() {
    return new Color(0, 0, 0, 0);
}

颜色类
public int getRGB() {
    return ((A << 24) | 0xFF) + ((R << 16) | 0xFF) + ((G << 8) | 0xFF) + (B | 0xFF);
}
4个回答

9
您可以使用此类型的函数来复制位图(或者根据您的使用方式,不使用函数)
private Bitmap ARGBBitmap(Bitmap img) {
  return img.copy(Bitmap.Config.ARGB_8888,true);
}

你读取的是什么文件格式?我之前使用过与你类似的代码,非常成功。你读取的是什么文件格式?你能否提供一张你遇到问题的图片样本?你是否通过调试器逐步执行该函数,以检查所有getPixel函数是否返回了你期望的结果? - Grambot

1
希望这可以帮到你,因为它对我有效。
Bitmap bitmap = Bitmap.createBitmap(marker.getMeasuredWidth(), marker.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

1

当我调整大小时,我想我失去了Alpha支持。我该怎么办? - omega
它不应该失去Alpha“支持”,你用于调整大小的代码是什么? - TehCoder
嗯,我有点傻。你正在创建一个尚未设置的新位图。 - TehCoder
当我调整大小时,我该如何指定该设置? - omega
在创建调整大小的图像时,Bitmap.Config... 没有第四个参数吗? - TehCoder
显示剩余5条评论

0
你可以使用这个:
public Bitmap highlightImage(Bitmap src) { 
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth() + 96, src.getHeight() + 96, Bitmap.Config.ARGB_8888); 
    return bmOut;
}

为什么要+96高度和宽度? - TehCoder
不需要使用+96。我已经使用它来缩放图像。这是必要的目的。 - Soham
哦,这只是一个例子,我的错。 - TehCoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接