我在android studio中制作了一个绘图应用程序。如何将绘图保存在内部存储中,然后在另一个活动中查看?我在互联网上有一些关于如何保存位图的代码,但它不起作用,我不知道我做错了什么。我已经陷入了这一部分。
以下是一些代码:
public onClick(View v){
if(v.getId() == R.id.btnBrush){
.....
}
else if(v.getId() == R.id.btnErase){
.....
}
else if(v.getId() == R.id.ibtnSave){
//save button clicked
final Dialog saveDialog = new Dialog(this);
saveDialog.setTitle("Save");
saveDialog.setContentView(R.layout.save_form);
saveDialog.show();
inputName = (EditText) findViewById(R.id.drawFile);
inputDate = (EditText) findViewById(R.id.date);
btnSave = (Button) saveDialog.findViewById(R.id.btnSave);
btnCancel = (Button) saveDialog.findViewById(R.id.btnCancel);
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
iView.setDrawingCacheEnabled(true);
save();
saveDialog.dismiss();
Intent intent = new Intent(DrawingPanel.this, Gallery.class);
startActivity(intent);
finish();
iView.destroyDrawingCache();
}
});
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
saveDialog.dismiss();
}
});
}
}
public void save(){
Bitmap bitmap = iView.getDrawingCache();
try{
FileOutputStream fos = openFileOutput(inputName.getText().toString() + ".png", Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
if(fos != null){
Toast saved = Toast.makeText(getApplicationContext(), "Image saved.", Toast.LENGTH_SHORT);
saved.show();
}
else{
Toast unsaved = Toast.makeText(getApplicationContext(), "Image not save.", Toast.LENGTH_SHORT);
unsaved.show();
}
fos.close();
}
catch(Exception e){
Log.e("save()", e.getMessage());
}
}
我想在它上面添加日期,但我不知道该怎么做。我很抱歉。我是Android工作室的新手,我不是很擅长这就是为什么我需要帮助,因为我真的想学习。
答案 0 :(得分:1)
public void save(){
Bitmap bitmap = iView.getDrawingCache();
try{
if(bitmap!=null){
File file=new File(Environment.getExternalStorageDirectory()+"/dirr");
if(!file.isDirectory()){
file.mkdir();
}
file=new File(Environment.getExternalStorageDirectory()+"/dirr",inputName.getText()+"_"+System.currentTimeMillis()+".jpg");
try
{
FileOutputStream fileOutputStream=new FileOutputStream(file);
if(bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream))
{
Toast saved = Toast.makeText(getApplicationContext(), "Image saved.", Toast.LENGTH_SHORT);
saved.show();
}
else{
Toast unsaved = Toast.makeText(getApplicationContext(), "Image not save.", Toast.LENGTH_SHORT);
unsaved.show();
}
}
catch(IOException e){
e.printStackTrace();
}
finally {
try {
if (fileOutputStream!= null) {
// fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e){
Log.e("save()", e.getMessage());
}
}
并在清单中添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
编辑:稍微清理一下代码,你也可以查看类似的问题: