Android實現下載圖片並儲存到SD卡中
阿新 • • 發佈:2019-01-25
在檔案裡設定一個點選方法已進行點選下載:
download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String filePath = imageInfo.get(currentItem).getBigImageUrl(); ImgDonwload.donwloadImg(ImageActivity.this,filePath); } });
下面是ImgDonwload.java圖片下載工具類:
package com.vimi8.app.utils.imagesUtils;import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log;import android.widget.Toast; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; /** * Created by vimi8 on 2017/6/9.*/ public class ImgDonwload { private static String filePath; private static Bitmap mBitmap; private static String mFileName="為米老鄉"; private static String mSaveMessage; private final static String TAG = "ImageActivity"; private static Context context; private static ProgressDialog mSaveDialog = null; public static void donwloadImg(Context contexts,String filePaths){ context = contexts; filePath = filePaths; mSaveDialog = ProgressDialog.show(context, "儲存圖片", "圖片正在儲存中,請稍等...", true); new Thread(saveFileRunnable).start(); } private static Runnable saveFileRunnable = new Runnable(){ @Override public void run() { try { byte[] data = getImage(filePath); if(data!=null){ mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap }else{ Toast.makeText(context, "Image error!", Toast.LENGTH_LONG).show(); } saveFile(mBitmap, mFileName); mSaveMessage = "圖片儲存成功!"; } catch (IOException e) { mSaveMessage = "圖片儲存失敗!"; e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } messageHandler.sendMessage(messageHandler.obtainMessage()); } }; private static Handler messageHandler = new Handler() { @Override public void handleMessage(Message msg) { mSaveDialog.dismiss(); Log.d(TAG, mSaveMessage); Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show(); } }; /** * Get image from newwork * @param path The path of image * @return byte[] * @throws Exception */ public static byte[] getImage(String path) throws Exception{ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); InputStream inStream = conn.getInputStream(); if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ return readStream(inStream); } return null; } /** * Get data from stream * @param inStream * @return byte[] * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } outStream.close(); inStream.close(); return outStream.toByteArray(); } /** * 儲存檔案 * @param bm * @param fileName * @throws IOException */ public static void saveFile(Bitmap bm, String fileName) throws IOException { File dirFile = new File(Environment.getExternalStorageDirectory().getPath()); if(!dirFile.exists()){ dirFile.mkdir(); } fileName = UUID.randomUUID().toString()+".jpg"; File jia=new File(Environment.getExternalStorageDirectory().getPath() +"/DCIM/VIMI8"); if(!jia.exists()){ //判斷資料夾是否存在,不存在則建立 jia.mkdirs(); } File myCaptureFile = new File(jia +"/"+ fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); //把圖片儲存後宣告這個廣播事件通知系統相簿有新圖片到來 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(myCaptureFile); intent.setData(uri); context.sendBroadcast(intent); } }
以上是取得的是byte陣列, 從byte陣列生成bitmap
以下是取得的是InputStream,直接從InputStream生成bitmap
package com.vimi8.app.utils.imagesUtils; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; /** * Created by vimi8 on 2017/6/9. */ public class ImgDonwloads { private static String filePath; private static Bitmap mBitmap; private static String mFileName="為米老鄉"; private static String mSaveMessage; private final static String TAG = "ImageActivity"; private static Context context; private static ProgressDialog mSaveDialog = null; public static void donwloadImg(Context contexts,String filePaths){ context = contexts; filePath = filePaths; mSaveDialog = ProgressDialog.show(context, "儲存圖片", "圖片正在儲存中,請稍等...", true); new Thread(saveFileRunnable).start(); } private static Runnable saveFileRunnable = new Runnable(){ @Override public void run() { try { mBitmap = BitmapFactory.decodeStream(getImageStream(filePath)); saveFile(mBitmap, mFileName); mSaveMessage = "圖片儲存成功!"; } catch (IOException e) { mSaveMessage = "圖片儲存失敗!"; e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } messageHandler.sendMessage(messageHandler.obtainMessage()); } }; private static Handler messageHandler = new Handler() { @Override public void handleMessage(Message msg) { mSaveDialog.dismiss(); Log.d(TAG, mSaveMessage); Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show(); } }; /** * Get image from newwork * @param path The path of image * @return InputStream * @throws Exception */ public static InputStream getImageStream(String path) throws Exception{ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ return conn.getInputStream(); } return null; } /** * 儲存檔案 * @param bm * @param fileName * @throws IOException */ public static void saveFile(Bitmap bm, String fileName) throws IOException { File dirFile = new File(Environment.getExternalStorageDirectory().getPath()); if(!dirFile.exists()){ dirFile.mkdir(); } fileName = UUID.randomUUID().toString()+".jpg"; File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() +"/DCIM/Camera/"+ fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); //把圖片儲存後宣告這個廣播事件通知系統相簿有新圖片到來 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(myCaptureFile); intent.setData(uri); context.sendBroadcast(intent); } }