안드로이드 학습의 압축 그림을 지정한 크기로

사진 압축에 관해서는 서버를 업로드할 때 크기 제한이 있기 때문에 여기서 두 가지 방법을 총결하였는데 개인적인 느낌 방법은 비교적 정확하다.
방법1:

	 *        
	 * 
	 *    bitmap  ,    64kb,     
	 * 
	 * @param bitmap
	 * @return
	 */
	private Bitmap ImageCompressL(Bitmap bitmap) {
		double targetwidth = Math.sqrt(64.00 * 1000);
		if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
			//         matrix  
			Matrix matrix = new Matrix();
			//        
			double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
					/ bitmap.getHeight());
			//       
			matrix.postScale((float) x, (float) x);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), matrix, true);
		}
		return bitmap;
	}

방법2:

	 *        (    )
	 * 
	 *    bitmap  ,    64kb,     
	 * 
	 * @param bitmap
	 */
	private Bitmap ImageCompress(Bitmap bitmap) {
		//            :KB
		double maxSize = 64.00;
		//  bitmap     ,  bitmap   (           )
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		//      KB
		double mid = b.length / 1024;
		//   bitmap                             
		if (mid > maxSize) {
			//   bitmap              
			double i = mid / maxSize;
			//                              
			bitmap = zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i),
					bitmap.getHeight() / Math.sqrt(i));
		}
		return bitmap;
	}

	/***
	 *        
	 * 
	 * @param bgimage
	 *            :     
	 * @param newWidth
	 *            :     
	 * @param newHeight
	 *            :     
	 * @return
	 */
	public Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
		//           
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		//         matrix  
		Matrix matrix = new Matrix();
		//        
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		//       
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

좋은 웹페이지 즐겨찾기