有时遇到了图片保存到本地的操作,明明很久之前的时候搞过,但是,每次还得重新打开浏览器搜索怎么操作,所以这次决定记录下来,争取下次可以自己独立写出来
保存图片
此时我们获取到图片的bitmap,然后调用方法将bitmap保存到本地
private void saveBitmap(Bitmap bitmap) {
String IMAGE_FILE_NAME = "screen_shot.jpg";
imgPath = Environment.getExternalStorageDirectory() + "/"
+ IMAGE_FILE_NAME; //此处是将图片保存到根目录
File f = new File(imgPath);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (fOut != null)
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fOut != null)
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
保存gif图
拿到gif图的byte数组,然后将此数组写到文件中
private void saveGif(byte[] bytes) {
String GIF_FILE_NAME = "screen_shot.gif";
imgPath = Environment.getExternalStorageDirectory() + "/"
+ GIF_FILE_NAME; //也是根目录
File file = new File(imgPath);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes, 0, bytes.length);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}