【Android】保存Bitmap到SD卡

ぃ、小莉子 提交于 2020-02-05 00:32:26

1.打开读写SD卡的权限  

需要在AndroidManifest.xml加入如下代码:

<uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


第一种方法:

public  void saveBitmap(String bitName, Bitmap mBitmap) {
File f = new File("/sdcard/" + bitName + ".png");
try {
f.createNewFile();
} catch (IOException e) {
Tools.ToastShort("在保存图片时出错:" + e.toString());
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}


第二种方法:

1、

public boolean writePngFile(File outFile) { // 将在屏幕上绘制的图形保存到SD卡
boolean resault = false; // 存储标识,false为保存失败
try {
FileOutputStream fos = new FileOutputStream(outFile); // 创建文件输出流(写文件)
if (editBitmap[0].compress(Bitmap.CompressFormat.PNG, 100, fos)) { // 将图片对象按PNG格式压缩(质量100%),写入文件
resault = true; // 存储成功
}
fos.flush(); // 刷新
fos.close();// 关闭流
} catch (Exception e) {
e.printStackTrace();
}
return resault;
}

2、

public void saveBitmap() {
final int fileIndex = getSharedPreferences("bitmapIndex",
Context.MODE_PRIVATE).getInt("index", 0); // 从共享偏好的记录中取出文件流水号,首次从0开始
new AlertDialog.Builder(this).setTitle("提示信息") // 创建并显示提示对话框
.setIcon(android.R.drawable.ic_menu_manage) // 设置图标
.setMessage("保存到SD卡: 钧瓷" + fileIndex + ".png?") // 设置提示信息
.setPositiveButton("确定", new OnClickListener() { // 按下“确定”按钮的处理
public void onClick(DialogInterface dialog,
int which) {
File outFile = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator
+ "钧瓷/钧瓷"
+ fileIndex
+ ".png");// 在SD卡上新建文件
if (MyCanvas.editArea.writePngFile(outFile)) { // 将绘制路径绘制到位图,并压缩保存
getSharedPreferences("bitmapIndex",
Context.MODE_PRIVATE)
.edit()
.putInt("index",
(fileIndex + 1) % 5)
.commit();// 流水号循环递增0~4
Tools.ToastShort("保存成功!");
isSave = false;
if (index == 2) {
ScreenNum = 1;
MyCanvas.menu.creat();
}
}
}
}).setNegativeButton("取消", new OnClickListener() {// 按下“取消”按钮的处理
public void onClick(DialogInterface dialog,
int which) {
isSave = false;
if (index == 2) {
ScreenNum = 1;
MyCanvas.menu.creat();
}
}
}).create().show();
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!