图片压缩

  1. //对图片进行压缩  
  2.            BitmapFactory.Options options = new BitmapFactory.Options();  
  3.            options.inJustDecodeBounds = true;  
  4.              
  5.            //获取这个图片的宽和高  
  6.            Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);//此时返回bm为空  
  7.            options.inJustDecodeBounds =false;  
  8.            //计算缩放比  
  9.            int be = (int)(options.outHeight / (float)200);  
  10.            if(be <= 0)  
  11.                 be =1;  
  12.            options.inSampleSize =be;  
  13.            //重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦  
  14.            bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);  
  15.            int w = bitmap.getWidth();  
  16.            int h=bitmap.getHeight();  
  17.            System.out.println(w+" "+h);  
  18.            myImageView.setImageBitmap(bitmap);  
  19.              
  20.              
  21.            //保存入sdCard  
  22.            File file2= new File("/sdcard/dcim/Camera/test.jpg");  
  23.            try {  
  24.             FileOutputStream out = new FileOutputStream(file2);  
  25.             if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){  
  26.                 out.flush();  
  27.                 out.close();  
  28.             }  
  29.         } catch (Exception e) {  
  30.             // TODO: handle exception  
  31.         }  
  32.              
  33.              
  34.         //读取sd卡  
  35.            File file =new File("/sdcard/dcim/Camera/test.jpg");  
  36.            int maxBufferSize = 16 * 1024;  
  37.               
  38.             int len = 0;  
  39.             ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  40.              BufferedInputStream bufferedInputStream;  
  41.             try {  
  42.                 bufferedInputStream = new BufferedInputStream(new FileInputStream(file));  
  43.                 int bytesAvailable = bufferedInputStream.available();  
  44.                 int bufferSize = Math.min(bytesAvailable, maxBufferSize);  
  45.                 byte[] buffer = new byte[bufferSize];  
  46.                 while ((len = bufferedInputStream.read(buffer)) != -1)  
  47.                 {  
  48.                     outStream.write(buffer, 0, bufferSize);  
  49.                 }  
  50.                  data = outStream.toByteArray();  
  51.                 outStream.close();  
  52.                 bufferedInputStream.close();  
  53.                   
  54.             } catch (FileNotFoundException e) {  
  55.                 e.printStackTrace();  
  56.             } catch (IOException e) {  
  57.                 e.printStackTrace();  
  58.             }  
posted @ 2013-03-25 23:13  青城幻影  阅读(180)  评论(0编辑  收藏  举报