public class DownGoodsImage {
private Context context;
private String filePath;
private String fileName;
private Bitmap mBitmap;
private String mSaveMessage = "失败";
private final String TAG = "DOWNLOADIMG";
private ProgressDialog mSaveDialog = null;
private Handler handler = null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
//myfile是我们要创建的文件夹的名字,这里的意思就是在这个路径下创建这个文件夹
File goodsImages = new File(path + "/goodsImages");
private List<File> list = new ArrayList<>();
private boolean download = true;
public void downGoodsImg(String filePaths,String fileName) {
filePath = filePaths;
fileName = fileName;
try {
list = FileUtils.getFile(goodsImages);
if (list != null && list.size() > 0){
for (int i = 0; i < list.size(); i ++){
if ((fileName + ".jpg").equals(list.get(i).getName())) {
Log.e("downloadImg", "本地已有此商品图片,无需再次下载");
download = false;
}
}
if (download){
if (!TextUtils.isEmpty(filePath)) { //网络图片
// 对资源链接
URL url = new URL(filePath);
//打开输入流
InputStream inputStream = url.openStream();
//对网上资源进行下载转换位图图片
mBitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
}
saveFile(mBitmap,fileName);
mSaveMessage = "图片保存成功!";
Log.i(TAG,"图片保存成功:" + fileName);
LogHandler.writeFile("downloadImg","图片保存成功:" + fileName);
}
}else {
if (!TextUtils.isEmpty(filePath)) { //网络图片
// 对资源链接
URL url = new URL(filePath);
//打开输入流
InputStream inputStream = url.openStream();
//对网上资源进行下载转换位图图片
mBitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
}
saveFile(mBitmap,fileName);
mSaveMessage = "图片保存成功!";
Log.i(TAG,"图片保存成功:" + fileName);
LogHandler.writeFile("downloadImg","图片保存成功:" + fileName);
}
} catch (IOException e) {
mSaveMessage = "图片保存失败!";
e.printStackTrace();
LogHandler.writeFile("downloadgoodsimage",e.getMessage());
} catch (Exception e) {
e.printStackTrace();
LogHandler.writeFile("downloadgoodsimage",e.getMessage());
}
}
/**
* 保存图片
* @param bm
* @throws IOException
*/
public void saveFile(Bitmap bm,String fileName ) throws IOException {
File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
if (!dirFile.exists()) {
boolean b = dirFile.mkdirs();
Log.i("创建文件夹","成功");
}
String name = fileName + ".jpg";
File myCaptureFile = new File(Environment.getExternalStorageDirectory() + "/goodsImages/" + name);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
}
}
Android 图片下载工具类
最新推荐文章于 2022-11-07 14:28:52 发布