public class AsynDownLoagPic extends AsyncTask<String, Void, Bitmap> { URL url = null; Context mContext; public AsynDownLoagPic(Context context) { mContext = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params) { //根据url路径,将图片保存到本地 InputStream inputStream = null; HttpURLConnection urlConnection = null; Bitmap bmp = null; try { url = new URL(params[0]); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10000); inputStream = urlConnection.getInputStream(); byte[] bt = getBytesFromStream(inputStream); LogUtils.e("bitmapCahche--->转换成bitmap对象------"); bmp = BitmapFactory.decodeByteArray(bt, 0, bt.length); } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { if (null != inputStream) { try { inputStream.close(); inputStream = null; } catch (IOException e) { e.printStackTrace(); } } if (null != urlConnection) { urlConnection.disconnect(); urlConnection = null; } } return bmp; } @Override protected void onPostExecute(Bitmap bitmap) { //将图片保存到本地 // saveMyBitmap((url.toString()), bitmap); saveImageToGallery(mContext,bitmap); }
//根据字节流保存图片
private byte[] getBytesFromStream(InputStream inputStream) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024 * 10]; int len = 0; while (len != -1) { try { len = inputStream.read(buf); if (len != -1) { baos.write(buf, 0, len); // baos.flush(); // LogUtils.e("bitmapCahche*-*-*-正在写入图片------" + buf.length); } } catch (IOException e) { e.printStackTrace(); LogUtils.e("bitmapCahche*-*-*-写入出错------" + e.toString()); len = -1; } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } LogUtils.e("bitmapCahche*-*-*-图片写入完毕------"); return baos.toByteArray(); }
//将图片保存到本地相册
public void saveImageToGallery(Context context, Bitmap bmp) { File appDir = new File("/mnt/sdcard/Diction", ""); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); // toast("保存成功"); ToastUtils.showShort(mContext,"保存成功。"); } catch (FileNotFoundException e) { // toast("保存失败"); ToastUtils.showShort(mContext,"保存失败。"); e.printStackTrace(); } catch (IOException e) { // toast("保存失败"); ToastUtils.showShort(mContext,"保存失败。"); e.printStackTrace(); } try { MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); } catch (FileNotFoundException e) { e.printStackTrace(); } context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); }