标题起的有点长,主要是不知道该怎么表达,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;
}