【问题标题】:Saving circle cropped image as JPEG format, background is not transparent in Android将圆形裁剪图像保存为 JPEG 格式,Android 中的背景不透明
【发布时间】:2021-03-12 06:45:06
【问题描述】:

我的要求是,需要将图像裁剪成圆形并保存为新图像。为此,我在 Android 中使用画布的 DrawRoundRect 方法裁剪了位图图像。

将图片裁剪为圆形并保存为PNG格式后,图片背景是透明的。但如果我以 JPEG 格式保存,图像背景是黑色的。请找到我的代码

RoundedBitmap(Bitmap bitmap)
    {
        Bitmap roundBitmap = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(roundBitmap);
        Paint paint = new Paint();
        paint.AntiAlias = true;
        RectF rectF = new RectF(0, 0, bitmap.Width, bitmap.Height);
        canvas.DrawRoundRect(rectF, bitmap.Width / 2, bitmap.Height / 2, paint);
         
        paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn));
        canvas.DrawBitmap(bitmap, 0, 0, paint);
        return roundedBitmap;
    }

使用 canvas.drawColor(Color.WHITE); 没有帮助。我需要 JPEG 格式的透明背景颜色。有可能吗?

问候,

婆罗提。

【问题讨论】:

  • 虽然可以存储 4 通道 JPEG 并将其解释为 RGBA,但这是非标准的,在许多应用程序中都不起作用。此外,有损 alpha 通常不是一个好主意。简而言之,如果您需要透明度,请使用 PNG。或者,如果您需要 JPEG,则存储为不透明的 JPEG,透明度为 PNG。使用透明度作为覆盖,并在运行时组合。

标签: java android image-processing xamarin.android jpeg


【解决方案1】:

PNG 支持透明背景,而 JPG 不支持。因此,您可以创建一个白色图像,然后在其上绘制原始图像。

  public static void convertBitmapToJpg(Bitmap bitmap, string newImgpath)
    {
                  
        Bitmap outB = bitmap.Copy(Bitmap.Config.Argb8888, true);
        Canvas canvas = new Canvas(outB);
        canvas.DrawColor(Color.White);
        canvas.DrawBitmap(bitmap, 0, 0, null);
        Java.IO.File file = new Java.IO.File(newImgpath);
        try
        {
            MemoryStream outFile = new MemoryStream();
            if (outB.Compress(Bitmap.CompressFormat.Jpeg, 100, outFile))
            {
                outFile.Flush();
                outFile.Close();
            }
        }
        catch (System.IO.FileNotFoundException e)
        {
           
        }
        catch (System.IO.IOException e)
        {
            
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多