2013-06-06 6 views
7

비트 맵의 ​​크기를 정확하게 200kb로 줄이려고합니다. sdcard에서 이미지를 가져 와서 압축하고 sdcard에 다른 이름으로 다른 디렉토리에 다시 저장하십시오. 압축은 잘 작동합니다 (이미지와 같은 3MB는 약 100KB로 압축됩니다). 나는이에 대한 코드의 다음 줄을 썼다 :안드로이드에서 비트 맵의 ​​크기를 지정된 크기로 줄이십시오.

/** 
    * reduces the size of the image 
    * @param image 
    * @param maxSize 
    * @return 
    */ 
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) { 
     int width = image.getWidth(); 
     int height = image.getHeight(); 

     float bitmapRatio = (float)width/(float) height; 
     if (bitmapRatio > 1) { 
      width = maxSize; 
      height = (int) (width/bitmapRatio); 
     } else { 
      height = maxSize; 
      width = (int) (height * bitmapRatio); 
     } 
     return Bitmap.createScaledBitmap(image, width, height, true); 
    } 

방법 전화 :

String imagefile ="/sdcard/DCIM/100ANDRO/DSC_0530.jpg"; 
Bitmap bm = ShrinkBitmap(imagefile, 300, 300); 

//this method compresses the image and saves into a location in sdcard 
    Bitmap ShrinkBitmap(String file, int width, int height){ 

     BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); 
      bmpFactoryOptions.inJustDecodeBounds = true; 
      Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); 

      int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height); 
      int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width); 

      if (heightRatio > 1 || widthRatio > 1) 
      { 
      if (heightRatio > widthRatio) 
      { 
       bmpFactoryOptions.inSampleSize = heightRatio; 
      } else { 
       bmpFactoryOptions.inSampleSize = widthRatio; 
      } 
      } 

      bmpFactoryOptions.inJustDecodeBounds = false; 
      bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); 

      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
      byte[] imageInByte = stream.toByteArray(); 
      //this gives the size of the compressed image in kb 
      long lengthbmp = imageInByte.length/1024; 

      try { 
       bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/compressed_new.jpg")); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


     return bitmap; 
     } 
+0

변경 그 이미지의 너비와 높이 .. – Riser

+0

당신은 200x200 이미지를 만들려고합니까? – TharakaNirmana

+0

예, 당신이 원하는대로 200kb .. 결과를 얻을 때까지 시도하십시오. – Riser

답변

16

내가 나를 위해 완벽하게 작동 답을 찾을

Bitmap converetdImage = getResizedBitmap(photo, 500); 
  • 사진이 당신의 비트 맵
+0

이 함수는 비트 맵 크기가 커지면 비트 맵 크기를 줄이지 만 더 작은 비트 맵은 줄입니다. 규격에 따라 확대 될 것인가? – NarendraJi

+0

왜 검은 비트 맵이됩니까? – Sermilion

+1

@TharakaNirmana maxSize 란 무엇입니까? 당신의 방법에서 500, 500kb 또는 500Mb로 전화를 걸 수 있습니까? – TheQ

관련 문제