Escala de imagen sin perder calidad de imagen no funcionó

¿Alguien sabe cómo escalar la imagen de mapa de bits sin perder la calidad de imagen? Actualmente frente a este problema , donde el tamaño de la imagen seleccionada tal vez demasiado grande causó la vuelta de la aplicación a otra actividad.

Así que ahora he intentado usar este método para escalar la imagen seleccionada sin perder su calidad. Tengo el código de aquí .

protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RESULT_LOAD_IMAGE: if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver() .query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); Bitmap a = (BitmapFactory.decodeFile(picturePath)); photo = scaleBitmap(a, 200, 200); imageView.setImageBitmap(photo); } break; } public static Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight) { Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888); float scaleX = newWidth / (float) bitmap.getWidth(); float scaleY = newHeight / (float) bitmap.getHeight(); float pivotX = 0; float pivotY = 0; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(scaleX, scaleY, pivotX, pivotY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bitmap, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG)); return scaledBitmap; } 

La respuesta parece útil para la mayoría de la gente, pero ¿por qué no funciona para mí? ¿He perdido algo?

imagen original

Imagen seleccionada en imageView

Pruebe esto para escalar el mapa de bits

 public static Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight) { float scaleX = ((float)newWidth) / bitmap.getWidth(); float scaleY = ((float)newHeight) / bitmap.getHeight(); Matrix scaleMatrix = new Matrix(); scaleMatrix.postScale(scaleX, scaleY); Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight() , scaleMatrix, true); return scaledBitmap; } 
 Use this it will definitely help you to reduce the size without loosing quality. public Bitmap compressImage(String imageUri) { String filePath = imageUri; // String filePath = getRealPathFromURI(imageUri); Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); // by setting this field as true, the actual bitmap pixels are not // loaded in the memory. Just the bounds are loaded. If // you try the use the bitmap here, you will get null. options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(filePath, options); int actualHeight = options.outHeight; int actualWidth = options.outWidth; // max Height and width values of the compressed image is taken as // 816x612 /* * float maxHeight = 816.0f; float maxWidth = 612.0f; */ float maxHeight = 1080.0f; float maxWidth = 800.0f; float imgRatio = actualWidth / (float) actualHeight; float maxRatio = maxWidth / (float) maxHeight; // width and height values are set maintaining the aspect ratio of the // image if (actualHeight > maxHeight || actualWidth > maxWidth) { if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight; actualWidth = (int) (imgRatio * actualWidth); actualHeight = (int) maxHeight; } else if (imgRatio > maxRatio) { imgRatio = maxWidth / actualWidth; actualHeight = (int) (imgRatio * actualHeight); actualWidth = (int) maxWidth; } else { actualHeight = (int) maxHeight; actualWidth = (int) maxWidth; } } // setting inSampleSize value allows to load a scaled down version of // the original image options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight); // inJustDecodeBounds set to false to load the actual bitmap options.inJustDecodeBounds = false; // this options allow android to claim the bitmap memory if it runs low // on memory options.inPurgeable = true; options.inInputShareable = true; options.inTempStorage = new byte[16 * 1024]; try { // load the bitmap from its path bmp = BitmapFactory.decodeFile(filePath, options); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } try { scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888); } catch (OutOfMemoryError exception) { exception.printStackTrace(); } float ratioX = actualWidth / (float) options.outWidth; float ratioY = actualHeight / (float) options.outHeight; float middleX = actualWidth / 2.0f; float middleY = actualHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); // check the rotation of the image and display it properly ExifInterface exif; try { exif = new ExifInterface(filePath); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); displayLogs("EXIF", "Exif: " + orientation); Matrix matrix = new Matrix(); if (orientation == 6) { matrix.postRotate(90); displayLogs("EXIF", "Exif: " + orientation); } else if (orientation == 3) { matrix.postRotate(180); displayLogs("EXIF", "Exif: " + orientation); } else if (orientation == 8) { matrix.postRotate(270); displayLogs("EXIF", "Exif: " + orientation); } scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true); } catch (IOException e) { e.printStackTrace(); } FileOutputStream out = null; String filename = getFilename(filePath); // File image = new File(getFilename(), System.currentTimeMillis() + // ".jpg"); try { out = new FileOutputStream(filename); // write the compressed bitmap at the destination specified by // filename. boolean didWrite = scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); out.close(); System.out.println(didWrite); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return scaledBitmap; } private String getRealPathFromURI(String contentURI) { Uri contentUri = Uri.parse(contentURI); Cursor cursor = getContentResolver().query(contentUri, null, null, null, null); if (cursor == null) { return contentUri.getPath(); } else { cursor.moveToFirst(); int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); return cursor.getString(index); } } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } final float totalPixels = width * height; final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } return inSampleSize; } public String getFilename(String originalname) { ImageCache imageCache = new ImageCache(this); File file = new File("Your folder path"); // return file; String uriSting = (file.getAbsolutePath() + "/" + "F_" + System.currentTimeMillis() + ".png"); return uriSting; } 

Por favor, intente esto

 public Bitmap scaleBitmap(Bitmap bitmap,int newWidth,int newHeight) { Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888); float ratioX = newWidth / (float) bitmap.getWidth(); float ratioY = newHeight / (float) bitmap.getHeight(); float middleX = newWidth / 2.0f; float middleY = newHeight / 2.0f; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(ratioX, ratioY, middleX, middleY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG)); return scaledBitmap; } 

Mientras que usted tiene demasiado imagen grande en ese momento usted debe requerido para manejar la política del escondrijo del mapa de bits. La gerencia del escondrijo del mapa es demasiado Complex.So en androide tenemos una biblioteca magnífica Picasso . Esta biblioteca es proporciona la gerencia incorporada del escondrijo. Esto será administrar su mapa de bits en el fondo y también es proporcionar característica de caché de imagen. Una vez que su imagen es la carga y de nuevo se carga esta misma imagen esto será obtener en la funcionalidad incorporada de cache.it no hay necesidad de cambiar en código.

Espero que esté claro con mi solución. La mejor de las suertes

Su problema es que no mantiene la relación de aspecto de la imagen original. En su código si usted necesita el ancho para ser 200, entonces la altura se debe calcular como esto:

 newHeight = ((float) originalHeight/(float) originalWidth) * (float) newWidth; 

Así que en su caso:

 float newHeight = ((float) a.getHeight()/(float) a.getWidth()) * (float) 200; 

Y luego llamar a su función de escala con width:200 y altura calculada a partir del valor original.

Después de que si la calidad es todavía baja, a continuación, experimente con el aumento de la anchura y parar cuando se obtiene la calidad necesaria.

  • Tome la imagen y convertir a Base64
  • Decodificar la matriz de bytes en el mapa de bits que se ha comprimido en Java
  • Qué tamaño almacenar imagen en el servidor para utilizar con la aplicación de Android
  • Android guardar y cargar las diferencias PNG bitmaps
  • Establecer imagen en vistas remotas
  • Ajuste automático de brillo, contraste y nitidez de una imagen de mapa de bits
  • Uso de Fresco de Facebook para cargar un mapa de bits
  • Android, ayuda a girar la imagen en el tacto
  • Seleccionar miniatura de la galería de Android
  • Android Opengl-es carga un poder de 2 no-textura
  • Escala de mapa de bits a 80 por ciento
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.