图片压缩保存读取操作

  1.            //对图片进行压缩  
  2.            BitmapFactory.Options options = new BitmapFactory.Options();  
  3.            options.inJustDecodeBounds = true;  
  4.            //获取这个图片的宽和高  
  5.            Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);//此时返回bm为空  
  6.            options.inJustDecodeBounds =false;  
  7.            //计算缩放比  
  8.            int be = (int)(options.outHeight / (float)200);  
  9.            if(be <= 0)  
  10.                 be =1;  
  11.            options.inSampleSize =be;  
  12.            //重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦  
  13.            bitmap = BitmapFactory.decodeFile("/sdcard/dcim/Camera/hello.jpg",options);  
  14.            int w = bitmap.getWidth();  
  15.            int h=bitmap.getHeight();  
  16.            System.out.println(w+" "+h);  
  17.            myImageView.setImageBitmap(bitmap);  
  18.              
  19.              
  20.            //保存入sdCard  
  21.            File file2= new File("/sdcard/dcim/Camera/test.jpg");  
  22.            try {  
  23.             FileOutputStream out = new FileOutputStream(file2);  
  24.             if(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)){  
  25.                 out.flush();  
  26.                 out.close();  
  27.             }  
  28.         } catch (Exception e) {  
  29.             // TODO: handle exception  
  30.         }  
  1.         //读取sd卡  
  2.            File file =new File("/sdcard/dcim/Camera/test.jpg");  
  3.            int maxBufferSize = 16 * 1024;  
  4.               
  5.             int len = 0;  
  6.             ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  7.              BufferedInputStream bufferedInputStream;  
  8.             try {  
  9.                 bufferedInputStream = new BufferedInputStream(new FileInputStream(file));  
  10.                 int bytesAvailable = bufferedInputStream.available();  
  11.                 int bufferSize = Math.min(bytesAvailable, maxBufferSize);  
  12.                 byte[] buffer = new byte[bufferSize];  
  13.                 while ((len = bufferedInputStream.read(buffer)) != -1)  
  14.                 {  
  15.                     outStream.write(buffer, 0, bufferSize);  
  16.                 }  
  17.                  data = outStream.toByteArray();  
  18.                 outStream.close();  
  19.                 bufferedInputStream.close();  
  20.                   
  21.             } catch (FileNotFoundException e) {  
  22.                 e.printStackTrace();  
  23.             } catch (IOException e) {  
  24.                 e.printStackTrace();  
  25.             }

你可能感兴趣的:(android,android,android)