android保存图片到sdCard上

  1 package com.jereh.tools;
  2 import java.io.BufferedInputStream;
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileNotFoundException;
  7 import java.io.FileOutputStream;
  8 import java.io.IOException;
  9 import java.io.OutputStream;
 10 
 11 import android.graphics.Bitmap;
 12 import android.graphics.BitmapFactory;
 13 import android.os.Environment;
 14 import android.os.StatFs;
 15 import android.util.Log;
 16 
 17 /**
 18  * Bitmap操作类, 不要轻易修改
 19  */
 20 public class BitmaptoCard {
 21     private static int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;
 22     private static int MB = 1024 * 1024;
 23     /**
 24      * 保存Bitmap到sdcard
 25      * 
 26      * @param dir
 27      * @param bm
 28      * @param filename
 29      * @param quantity
 30      */
 31     public static boolean saveBmpToSd(String dir, Bitmap bm, String filename,
 32             int quantity, boolean recyle) {
 33         boolean ret = true;
 34         if (bm == null) {
 35             return false;
 36         }
 37 
 38         if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
 39             bm.recycle();
 40             bm = null;
 41             return false;
 42         }
 43 
 44         File dirPath = new File(dir);
 45 
 46         if (!exists(dir)) {
 47             dirPath.mkdirs();
 48         }
 49 
 50         if (!dir.endsWith(File.separator)) {
 51             dir += File.separator;
 52         }
 53 
 54         File file = new File(dir + filename);
 55         OutputStream outStream = null;
 56         try {
 57             file.createNewFile();
 58             outStream = new FileOutputStream(file);
 59             bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
 60             outStream.flush();
 61             outStream.close();
 62         } catch (FileNotFoundException e) {
 63             e.printStackTrace();
 64             ret = false;
 65         } catch (IOException e) {
 66             e.printStackTrace();
 67             ret = false;
 68         } catch (OutOfMemoryError e) {
 69             e.printStackTrace();
 70             ret = false;
 71         } finally {
 72             if (outStream != null) {
 73                 try {
 74                     outStream.close();
 75                 } catch (IOException e) {
 76                     // TODO Auto-generated catch block
 77                     e.printStackTrace();
 78                 }
 79             }
 80             if (recyle && !bm.isRecycled()) {
 81                 bm.recycle();
 82                 bm = null;
 83                 Log.e("BitmaptoCard", "saveBmpToSd, recyle");
 84             }
 85         }
 86 
 87         return ret;
 88     }
 89 
 90     /**
 91      * 保存Bitmap到sdcard
 92      * 
 93      * @param dir
 94      * @param bm
 95      * @param filename
 96      * @param quantity
 97      */
 98     public static boolean saveBmpToSd(String dir, Bitmap bm, String filename,
 99             int quantity) {
100         return saveBmpToSd(dir, bm, filename, quantity, false);
101     }
102 
103     /**
104      * 保存Bitmap到sdcard
105      * 
106      * @param dir
107      * @param bm
108      * @param filename
109      * @param quantity
110      */
111     public static boolean saveBmpToSd(String dir, String srcFile,
112             String filename, int quantity) {
113         if (srcFile == null) {
114             return false;
115         }
116         Bitmap bmp = BitmapFactory.decodeFile(srcFile);
117         return saveBmpToSd(dir, bmp, filename, quantity);
118     }
119 
120     /**
121      * 保存Bitmap到sdcard
122      * 
123      * @param dir
124      * @param bm
125      * @param filename
126      * @param quantity
127      */
128     public static boolean saveBmpToSd(String dir, String srcFile,
129             String filename, int quantity, boolean recyle) {
130         if (srcFile == null) {
131             return false;
132         }
133         Bitmap bmp = BitmapFactory.decodeFile(srcFile);
134         return saveBmpToSd(dir, bmp, filename, quantity, recyle);
135     }
136 
137     /**
138      * 保存Bitmap到sdcard
139      * 
140      * @param dir
141      * @param bm
142      * @param filename
143      * @param quantity
144      */
145     public static boolean saveBmpToSd(String dir, String srcFile,
146             String filename, int quantity, float size, boolean recyle) {
147         if (srcFile == null) {
148             return false;
149         }
150         Bitmap bmp = convertToThumb(readFileToBuffer(srcFile), size);
151         return saveBmpToSd(dir, bmp, filename, quantity, recyle);
152     }
153 
154     /**
155      * 保存Bitmap到sdcard
156      * 
157      * @param dir
158      * @param bm
159      * @param filename
160      * @param quantity
161      */
162     public static boolean saveBmpToSd(String dir, String srcFile,
163             String filename, int quantity, float size) {
164         if (srcFile == null) {
165             return false;
166         }
167         Bitmap bmp = convertToThumb(readFileToBuffer(srcFile), size);
168         return saveBmpToSd(dir, bmp, filename, quantity);
169     }
170 
171     /**
172      * 保存Bitmap到sdcard
173      * 
174      * @param dir
175      * @param bm
176      * @param filename
177      * @param quantity
178      */
179     public static boolean saveBmpToSd(String dir, Bitmap bmp, String filename,
180             int quantity, float size) {
181         if (bmp == null) {
182             return false;
183         }
184         bmp = convertToThumb(readBitmap(bmp), size);
185         return saveBmpToSd(dir, bmp, filename, quantity);
186     }
187 
188     /**
189      * 获取sdcard路径
190      * 
191      * @return
192      */
193     public static String getSdcardPath() {
194         return Environment.getExternalStorageDirectory().getPath()
195                 + File.separator;
196     }
197 
198     /**
199      * 验证文件是否存在
200      * 
201      * @param url
202      * @return
203      */
204     public static boolean exists(String url) {
205         File file = new File(url);
206 
207         return file.exists();
208     }
209 
210     /**
211      * 检测sdcard可用空间
212      * 
213      * @return
214      */
215     public static int freeSpaceOnSd() {
216         StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
217                 .getPath());
218 
219         double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
220                 .getBlockSize()) / MB;
221 
222         return (int) sdFreeMB;
223     }
224 
225     /**
226      * Bitmap --> byte[]
227      * 
228      * @param bmp
229      * @return
230      */
231     private static byte[] readBitmap(Bitmap bmp) {
232         ByteArrayOutputStream baos = new ByteArrayOutputStream();
233         bmp.compress(Bitmap.CompressFormat.JPEG, 60, baos);
234         try {
235             baos.flush();
236             baos.close();
237         } catch (IOException e) {
238             e.printStackTrace();
239         }
240         return baos.toByteArray();
241     }
242 
243     /**
244      * 保存Bitmap到sdcard
245      * 
246      * @param dir
247      * @param bm
248      * @param filename
249      * @param quantity
250      */
251     public static boolean saveBmpToSd(String filePath, Bitmap bm, int quantity) {
252         if (filePath == null) {
253             return false;
254         }
255 
256         int end = filePath.lastIndexOf(File.separator);
257         String dir = filePath.substring(0, end);
258         String filename = filePath.substring(end);
259 
260         return saveBmpToSd(dir, bm, filename, quantity);
261     }
262 
263     /**
264      * @description: 通过文件路径将对应文件转为byte[]
265      * @param fileName
266      * @return
267      */
268     public static byte[] getByte(String fileName) {
269         if (fileName == null || "".equals(fileName)) {
270             return new byte[0];
271         }
272         File file = new File(fileName);
273         if (file.exists()) {
274             try {
275                 FileInputStream fin = new FileInputStream(fileName);
276                 int length = fin.available();
277                 byte[] buffer = new byte[length];
278                 fin.read(buffer);
279                 // res = EncodingUtils.getString(buffer, "UTF-8");
280                 fin.close();
281                 return buffer;
282             } catch (Exception e) {
283                 Log.e("BitmaptoCard", "getByte fail:" + fileName);
284                 return new byte[0];
285             }
286         } else {
287             Log.e("BitmaptoCard", "getByte file no exists :" + fileName);
288             return new byte[0];
289         }
290 
291     }
292 
293     /**
294      * 将图片、语音或者文件读入到byte缓冲数组
295      * 
296      * @param filePath
297      * @return
298      */
299     public static byte[] readFileToBuffer(String filePath) {
300         if (filePath == null || filePath.trim().equals("")) {
301             Log.e("BitmaptoCard", "readFileToBuffer, path is null:" + filePath);
302             return null;
303         }
304         File file = new File(filePath);
305         if (!file.exists()) {
306             Log.e("BitmaptoCard", "readFileToBuffer, file is not exists:"
307                     + filePath);
308             return null;
309         }
310 
311         byte[] buffer = new byte[(int) file.length()];
312         FileInputStream fis = null;
313         try {
314             fis = new FileInputStream(file);
315             BufferedInputStream bis = new BufferedInputStream(fis);
316             bis.read(buffer);
317             bis.close();
318         } catch (Exception e) {
319             e.printStackTrace();
320         }
321 
322         return buffer;
323     }
324 
325     /**
326      * 检查图片是否超过一定值,是则缩小
327      * 
328      * @param view
329      * @param strFileName
330      */
331     public static Bitmap convertToThumb(byte[] buffer, float size) {
332         // 获取原图宽度
333         BitmapFactory.Options options = new BitmapFactory.Options();
334         options.inJustDecodeBounds = true;
335 
336         options.inPurgeable = true;
337         options.inInputShareable = true;
338 
339         Bitmap bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length,
340                 options);
341 
342         // 计算缩放比例
343         float reSize = options.outWidth / size;
344 
345         if (options.outWidth > options.outHeight) {
346             reSize = options.outHeight / size;
347         }
348 
349         if (reSize <= 0) {
350             reSize = 1;
351         }
352 
353         Log.d("BitmaptoCard", "convertToThumb, reSize:" + reSize);
354 
355         // 缩放
356         options.inJustDecodeBounds = false;
357         options.inSampleSize = (int) reSize;
358 
359         if (bm != null && !bm.isRecycled()) {
360             bm.recycle();
361             bm = null;
362             Log.e("BitmaptoCard", "convertToThumb, recyle");
363         }
364 
365         bm = BitmapFactory.decodeByteArray(buffer, 0, buffer.length, options);
366 
367         if (bm == null) {
368             Log.e("BitmaptoCard", "convertToThumb, decode fail:" + null);
369             return null;
370         }
371 
372         return bm;
373     }
374 
375 }

 

public class FileUtils {
    public static int saveToSdCard(String fileName,Bitmap bitmap){
        int ret=0;
        PrintStream out=null;
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return -1;
        }
        File file=new File(Environment.getExternalStorageDirectory().toString()+File.separator+fileName);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdir();
        }
        try {
            out=new PrintStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            ret=-2;
        }finally{
            out.flush();
            out.close();
            if(!bitmap.isRecycled()) bitmap.recycle();
        }
        
        return ret;
    }
    
    public static Bitmap readImageFile(String fileName){
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return null;
        }
        File file=new File(Environment.getExternalStorageDirectory().toString()+File.separator+fileName);
        if(!file.exists()){
            return null;
        }
        return BitmapFactory.decodeFile(fileName);
    }
    
}

 

posted @ 2015-07-20 17:35  也猫不要吃鱼  阅读(300)  评论(0)    收藏  举报