[英]Saving circle cropped image as JPEG format, background is not transparent in Android
我的要求是,需要將圖像裁剪成圓形並保存為新圖像。 為此,我在 Android 中使用 canvas 的 DrawRoundRect 方法裁剪了 bitmap 圖像。
將圖像裁剪為圓形並保存為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 格式的透明背景顏色。 可能嗎。?
問候,
婆羅地。
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)
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.