好久没有冒泡了,最近公司开发模式变成了敏捷开发,技术人员的时间已经成为压缩饼干了,没有太多的事情去整理在开发中遇到的问题和使用到的技术点了.今天有一点点事件来整理了开发中用到的一个知识点,网上图片保存,或者本地图片保存到指定文件夹.
public class ImageHelper {
private Context mContext;
private static ImageHelper instance = null;
public synchronized static ImageHelper getInstance(Context context) {
if (instance == null) {
instance = new ImageHelper(context.getApplicationContext());
}
return instance;
}
private ImageHelper(Context context) {
mContext = context;
}
public Bitmap loadImage(String filePathOrUrl) throws ClientProtocolException, IOException, HttpRequestException {
Bitmap ret = null;
if (filePathOrUrl.startsWith("http")) {
// 是否有缓存
String fileName = generateDiskCacheKey(filePathOrUrl, 0, 0, false);
File file = null;
file = new File(mContext.getCacheDir(), fileName);// 保存文件
if (!file.exists()) {
HttpUtil.download(filePathOrUrl, file);
ret = BitmapFactory.decodeFile(file.getAbsolutePath());
} else {
String imagePath = mContext.getCacheDir() + "/" + fileName;
ret = BitmapFactory.decodeFile(imagePath);
}
} else {
ret = BitmapFactory.decodeFile(filePathOrUrl);
}
return ret;
}
}
public class SaveImage {
BaseActivity activity;
public SaveImage(Activity activity) {
this.activity = (BaseActivity)activity;
}
/**
*
* @param context
* @param filePath 网络图片地址或者本地图片
*/
public void saveFile(Context context, String filePath){
Bitmap bm = null;
ImageHelper imageHelper = ImageHelper.getInstance(context);
String pathStr = getSystemPhotoPath();
try {
bm = imageHelper.loadImage(filePath);
} catch (IOException e) {
e.printStackTrace();
}
File foder = new File(pathStr);
if (!foder.exists()) {
foder.mkdirs();
}
String fileName = System.currentTimeMillis() + ".jpg";
File myCaptureFile = new File(foder, fileName);
BufferedOutputStream bos = null;
if (!myCaptureFile.exists()) {
try {
myCaptureFile.createNewFile();
bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 最后通知图库更新
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), myCaptureFile.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(myCaptureFile);
intent.setData(uri);
activity.sendBroadcast(intent);
activity.showToast("保存成功了...");
}
private String getSystemPhotoPath() {
String pathSaveParent = null;
try {
pathSaveParent = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
.getAbsolutePath();
} catch (Exception e) {
activity.showToast("当前系统相册路径不可用,添加失败");
}
return pathSaveParent;
}
}