Android 将位图保存到文件,生成黑色图像
我使用android的API示例在响应触摸事件的视图上绘图。基本上,它所做的是每次我触摸屏幕时,它都会在我的屏幕上画一个圆圈(因此,它会画一个带有透明背景的圆圈,看起来就像内容被保留了一样) 现在的问题是当我试图将其保存为图像时。我尝试了JPG和PNG,我得到了黑色图片。不知怎的,我想它让所有透明的东西都变成了黑色 是否有任何方法可以将此位图保存为图像(最好是JPG)?当你看图像本身时,它根本没有透明度 多谢各位 按要求添加代码 我初始化视图如下Android 将位图保存到文件,生成黑色图像,android,android-bitmap,Android,Android Bitmap,我使用android的API示例在响应触摸事件的视图上绘图。基本上,它所做的是每次我触摸屏幕时,它都会在我的屏幕上画一个圆圈(因此,它会画一个带有透明背景的圆圈,看起来就像内容被保留了一样) 现在的问题是当我试图将其保存为图像时。我尝试了JPG和PNG,我得到了黑色图片。不知怎的,我想它让所有透明的东西都变成了黑色 是否有任何方法可以将此位图保存为图像(最好是JPG)?当你看图像本身时,它根本没有透明度 多谢各位 按要求添加代码 我初始化视图如下 @Override prote
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= w && curH >= h) {
return;
}
if (curW < w) curW = w;
if (curH < h) curH = h;
Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
Canvas newCanvas = new Canvas();
newCanvas.setBitmap(newBitmap);
if (mBitmap != null) {
newCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = newBitmap;
mCanvas = newCanvas;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
}
void paintmycolor(float x, float y, float major, float minor){
mPaint.setColor(myDrawColor);
mPaint.setAlpha(Math.min((int) (pressure * 128), 255));
canvas.save(Canvas.MATRIX_SAVE_FLAG);
RectF mReusableOvalRect = new RectF();
canvas.rotate((float) (orientation * 180 / Math.PI), x, y);
mReusableOvalRect.left = x - minor / 2;
mReusableOvalRect.right = x + minor / 2;
mReusableOvalRect.top = y - major / 2;
mReusableOvalRect.bottom = y + major / 2;
canvas.drawOval(mReusableOvalRect, paint);
canvas.restore();
}
我保存如下
公共文件saveBitmap()引发IOException{
File path=Environment.getExternalStoragePublicDirectory(android.os.Environment.DCIM);
File myDirectory = new File(path,mContext.getString(R.string.app_name));
if(!myDirectory.exists()){
myDirectory.mkdirs();
}
File output;
do {
int rand = new Random().nextInt();
output = new File(myDirectory,rand+".jpg");
}while(output.exists());
BufferedOutputStream ous = null;
try {
ous=new BufferedOutputStream(new FileOutputStream(output));
mBitmap.compress(CompressFormat.JPEG, 100, ous);
ous.flush();
ous.close();
return output;
} finally {
if (ous!=null) {
try {
ous.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("closing", e.getMessage());
}
}
}
}
找到答案。当您创建位图时,虽然它显示为白色,但实际上是透明背景。这就是为什么我得到黑色的原因。我找到了一个解决方案,在不将颜色更改为白色的情况下保留透明度(可能您会将其用于非白色背景布局): 创建位图以将其保存在内存中时,以及保存位图之前,为其指定以下条件:
mBitmap.setHasAlpha(true);
这将使图像在设备上时保持其透明度,这将导致图像在从内存中检索时具有透明度
毕竟,别忘了将其另存为PNG:
mBitmap.compress(Bitmap.CompressFormat.PNG, 80, ous);
您是否正在绘制圆圈用户视图…?请共享您的绘制圆圈以便更好地理解显示一些代码。一些问题:1)JPG,不支持透明,因此您将获得黑色背景。如果您的圆圈是黑色的,那么您将无法找到它。2)您是否使用SurfaceView?还是使用Canvas?SurfaceView实际上是绘制的在画布中添加一个黑色图像,如果使用画布捕获位图,则SurfaceView层尚未渲染,因此位图将为黑色。我添加了相关代码。这是一个普通视图,我正在扩展创建位图后,将其全部涂成白色,这样您就不会使用trasnprency@Snake,哥们!我需要透明的图像你就像WhatsApp里的贴纸。那怎么解决呢?