请帮助我找到promblem或编辑我的代码,将画布保存到png flie。
(嗯,我可以保存但不能打开它,我的png是黑色的。)
对不起我的工作。
CanvasView.class
public Bitmap saveSignature() {
Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
this.draw(canvas);
Calendar calendar=Calendar.getInstance();
//File file = new File(Environment.getExternalStorageDirectory() + "/Pictures/sign"+calendar.getTimeInMillis()+".png");
File file = Environment.getExternalStorageDirectory();
File newFile = new File(file, "test"+calendar.getTimeInMillis()+".png");
try {
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Log.e("file", file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", e.getLocalizedMessage());
}
return bitmap;
}
Main.class
public void saveCanvas(View view) {
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == 1) {
ivSignature.setImageBitmap(canvasView.saveSignature());
canvasView.clearCanvas();
} else {
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
}
}
答案 0 :(得分:1)
PNG是黑色的,因为它是透明的。初始化时将其着色。 您可以使用以下代码段将当前画布保存为.png图像。 它安静简单。
customCanvas.setDrawingCacheEnabled(true);
String imgSaved = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), customCanvas.getDrawingCache(),UUID.randomUUID().toString()+".png", "drawing");
if(imgSaved!=null){
//do something here
}
else{
//do something here
}
答案 1 :(得分:-1)
参考以下代码段
将画布保存到图像RelativeLayout z = (RelativeLayout) findViewById(R.id.CardMakerrl);
z.setDrawingCacheEnabled(true);
z.buildDrawingCache();
Bitmap bitmapSetDrawingChache = Bitmap.createBitmap(z.getDrawingCache());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
bitmapSetDrawingChache.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
}catch (Exception e)
{
Toast.makeText(CardMaker.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
// saving in sdcard
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "My Folder" + File.separator);
if(!file.exists())
file.mkdirs();
String imageName = "Data-" + DateFormat.getDateTimeInstance().format(new Date()) + ".jpg";
final File fileImagePath = new File(file.getAbsolutePath(), imageName);
FileOutputStream fileOutputStream = new FileOutputStream(fileImagePath);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
fileOutputStream.close();