標題起的有點長,主要是不知道該怎麼表達,android的圖片獲取和保存相信很多人都做過.有時候我們在對圖片保存時會將圖片壓縮一下,也就是這個壓縮,
會造成很多問題.通常情況下,網絡獲取圖片均爲jpeg格式,而有些時候app爲了達到某些效果,會給出png的透明邊圖片,可是我們在壓縮的時候依然用jpeg的
格式進行的壓縮.這就是問題的根源.但是我們也不可能再寫一套保存邏輯用png的格式,再說了,我們也不知道哪個圖是png格式,哪個圖是jpeg格式,對不對?
以前做項目的時候遇到過,解決了.也就沒再關心過這個東西.今天突然想到一些問題,就在網上搜索有沒有更好的解決方式,可是一個都沒搜到,連解決這種保存方式的
帖子都沒有,這頁促使我把我以前的解決方式分享給大家.有更好的方式大家可以互相討論.具體請看代碼:
if(is!=null){
BitmapFactory.Options options = new BitmapFactory.Options();
options .inPreferredConfig = Bitmap.Config.RGB_565;
options .inPurgeable = true;
options .inInputShareable = true;
bitmap= BitmapFactory.decodeStream(is, null , options );
is.close();
UtilFile.saveImgToCompletePath(bitmap, path,
UtilImage.getImgFormat(options));
}
public static CompressFormat getImgFormat(BitmapFactory.Options options){
String type = options.outMimeType;
if(type!=null&&type.indexOf("png")>-1) return CompressFormat.PNG;
else return CompressFormat.JPEG;
}
/**
* 保存圖片到sd卡
* @param bitmap
* @param completePath : 完整路徑
* @param compressFormat
*/
public static void saveImgToCompletePath(Bitmap bitmap,String
completePath,CompressFormat format) {
File file = new File(completePath);
File parentFile = file.getParentFile();
if (!parentFile.exists())
parentFile.mkdirs();
if (bitmap != null) {
try{
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(format, 100, fos);
}catch(Exception e){
InputStream is = UtilImage.bitmapToInputStream(bitmap,
format,0);
saveFileToCompletePath(getSDDir() +
file.getAbsolutePath(), is, false);
}
}
}
/**
* 在SD卡上存文件
* @param completePath : 完整路徑
* @param is
* @return 成功file,失敗null
*/
public static File saveFileToCompletePath(String completePath, InputStream is, boolean append) {
File file = new File(completePath);
File parentFile = file.getParentFile();
if (!parentFile.exists())
parentFile.mkdirs();
if (is != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, append);
byte[] b = new byte[1024];
int len = -1;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
is.close();
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else
return null;
}