2017-04-21 58 views
0

我需要使用多边形遮罩保存Bitmap。我试过this question,但是那里的图像被绘制而不是被保存。我认为这将是这样的:使用PorterDuffXfermode和路径(行集合)剪切后保存位图

//Creates Bitmaps 
BitmapFactory.Options options = new BitmapFactory.Options(); 
Bitmap original = BitmapFactory.decodeFile(path, options); 
Bitmap result = Bitmap.createBitmap(200, 200, Config.ARGB_8888); 

//Creates the file 
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "name".png"); 
OutputStream fOut = new FileOutputStream(file); 

//Sets PorterDuff 
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
paint.setAntiAlias(true); 
paint.setStyle(Paint.Style.FILL);; 
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); 

//Sets the polygonal path 
Path path = new Path(); 
path.moveTo(200,200); 
path.lineTo(400,200); 
path.lineTo(400,400); 
path.lineTo(200,400); 
path.close(); 

//Saves the image. The problem is here: how can one define result to be the cropping of the image with the path? 
result.compress(Bitmap.CompressFormat.PNG, 100, fOut); 
fOut.flush(); 
if (fOut != null) { 
    fOut.close(); 
} 
// 

所以,我应该如何着手? 如何定义result是用图像裁剪的路径?

回答

0

这是不是最好的解决方案,但它的工作:

BitmapFactory.Options options = new BitmapFactory.Options(); 
Bitmap original = BitmapFactory.decodeFile(path, options); 
try { 
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "name".png"); 
    OutputStream fOut = new FileOutputStream(file); 

    //The size of the two bitmaps below should be equal 
    Bitmap resultImg = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888); 
    Bitmap maskImg = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888); 

    Canvas mCanvas = new Canvas(resultImg); 
    Canvas maskCanvas = new Canvas(maskImg); 

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    paint.setAntiAlias(true); 
    paint.setStyle(Paint.Style.FILL); 
    paint.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP)); 

    Path path = new Path(); 
    path.moveTo(200,200); 
    path.lineTo(400,200); 
    path.lineTo(400,400); 
    path.lineTo(200,400); 
    path.close(); 

    maskCanvas.drawPath(path, paint); 
    mCanvas.drawBitmap(original, 0, 0, null); 
    //The following should have appropriate x,y for the path(here 200) 
    mCanvas.drawBitmap(maskImg, 200, 200, paint); 

    resultImg.compress(Bitmap.CompressFormat.PNG, 100, fOut); 
    fOut.flush(); 

if (fOut != null) { 
    fOut.close(); 
} 
} catch (IOException e){ 
    e.printStackTrace(); 
}