Bharathi
Bharathi

Reputation: 1328

Saving circle cropped image as JPEG format, background is not transparent in Android

My requirement is, need to crop the image in circle shape and save as new image. For that, i have cropped the bitmap image using DrawRoundRect method of canvas in Android.

After cropped the image as circle and saving in PNG format, image background is transparent. But if i saved in JPEG format, image background was black. Please find my code

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

Using canvas.drawColor(Color.WHITE); not helped. I need transparent background color for JPEG format. Is it possible.?

Regards,

Bharathi.

Upvotes: 1

Views: 173

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

PNG support transparent background while JPG doesn't . So you could create a white image, and then paint the original onto it.

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

Upvotes: 0

Related Questions