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();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());}}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();}
}