Cómo cambiar el tamaño de un mapa de bits en Android?

Tengo un mapa de bits tomado de una cadena Base64 de mi base de datos remota, ( encodedImage es la cadena que representa la imagen con Base64):

 profileImage = (ImageView)findViewById(R.id.profileImage); byte[] imageAsBytes=null; try { imageAsBytes = Base64.decode(encodedImage.getBytes()); } catch (IOException e) {e.printStackTrace();} profileImage.setImageBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) ); 

ProfileImage es mi ImageView

Ok, pero tengo que cambiar el tamaño de esta imagen antes de mostrarla en mi ImageView de mi diseño. Tengo que cambiar el tamaño a 120×120.

¿Puede alguien decirme el código para cambiar el tamaño?

Los ejemplos que encontré no se pueden aplicar a un mapa de bits obtenido en cadena base64.

Cambio:

 profileImage.setImageBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) 

A:

 Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false)); 
 public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.postScale(scaleWidth, scaleHeight); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, false); bm.recycle(); return resizedBitmap; } 

EDIT: como lo sugiere @aveschini, he añadido bm.recycle(); Para fugas de memoria. Observe por favor que en caso de que usted esté utilizando el objeto anterior para algunos otros propósitos, después maneje en consecuencia.

Si ya tiene un mapa de bits, puede utilizar el código siguiente para cambiar el tamaño:

 Bitmap originalBitmap = <original initialization>; Bitmap resizedBitmap = Bitmap.createScaledBitmap( originalBitmap, newWidth, newHeight, false); 

Escala basada en relación de aspecto :

 float aspectRatio = yourSelectedImage.getWidth() / (float) yourSelectedImage.getHeight(); int width = 480; int height = Math.round(width / aspectRatio); yourSelectedImage = Bitmap.createScaledBitmap( yourSelectedImage, width, height, false); 

Para utilizar la altura como base intead del ancho cambie a:

 int height = 480; int width = Math.round(height * aspectRatio); 

Escale un mapa de bits con un tamaño y un ancho máximo de destino, manteniendo la relación de aspecto:

 int maxHeight = 2000; int maxWidth = 2000; float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight())); Matrix matrix = new Matrix(); matrix.postScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 

Pruebe este código:

 BitmapDrawable drawable = (BitmapDrawable) imgview.getDrawable(); Bitmap bmp = drawable.getBitmap(); Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false); 

Espero que sea útil.

Alguien preguntó cómo mantener la relación de aspecto en esta situación:

Calcule el factor que está utilizando para el escalado y utilícelo para ambas dimensiones. Supongamos que desea que una imagen sea el 20% de la pantalla en altura

 int scaleToUse = 20; // this will be our percentage Bitmap bmp = BitmapFactory.decodeResource( context.getResources(), R.drawable.mypng); int sizeY = screenResolution.y * scaleToUse / 100; int sizeX = bmp.getWidth() * sizeY / bmp.getHeight(); Bitmap scaled = Bitmap.createScaledBitmap(bmp, sizeX, sizeY, false); 

Para obtener la resolución de pantalla que tiene esta solución: Obtener las dimensiones de la pantalla en píxeles

Intente esto: Esta función redimensiona un mapa de bits proporcionalmente. Cuando el último parámetro se ajusta a "X", el newDimensionXorY se trata como nuevo ancho y cuando se establece en "Y" una nueva altura.

 public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } 
  public Bitmap scaleBitmap(Bitmap mBitmap) { int ScaleSize = 250;//max Height or width to Scale int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); float excessSizeRatio = width > height ? width / ScaleSize : height / ScaleSize; Bitmap bitmap = Bitmap.createBitmap( mBitmap, 0, 0,(int) (width/excessSizeRatio),(int) (height/excessSizeRatio)); //mBitmap.recycle(); if you are not using mBitmap Obj return bitmap; } 
 profileImage.setImageBitmap( Bitmap.createScaledBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 80, 80, false ) ); 

A partir de la API 19, Bitmap setWidth (int width) y setHeight (int height) existen. http://developer.android.com/reference/android/graphics/Bitmap.html

Redimensionar mapa de bits basado en cualquier tamaño de pantalla

 public Bitmap bitmapResize(Bitmap imageBitmap) { Bitmap bitmap = imageBitmap; float lengthbmp = bitmap.getHeight(); float widthbmp = bitmap.getWidth(); // Get Screen width DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels / 3; float width = displaymetrics.widthPixels / 3; int convertHighet = (int) hight, convertWidth = (int) width; // high length if (lengthbmp > hight) { convertHighet = (int) hight - 20; bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true); } // high width if (widthbmp > width) { convertWidth = (int) width - 20; bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true); } return bitmap; } 
 public static Bitmap resizeBitmapByScale( Bitmap bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap)); Canvas canvas = new Canvas(target); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return target; } private static Bitmap.Config getConfig(Bitmap bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) { config = Bitmap.Config.ARGB_8888; } return config; } 
  • Java.lang.OutOfMemoryError Incluso en un bloque try-catch?
  • BitmapFactory.decodeFile devuelve null
  • Copiar una matriz de bits de la imagen de mapa de bits en la programación ANDROID
  • Android, guardar la imagen de la vista como archivo png
  • Error de error de mapa de bits inmutable
  • Dibujar círculo en mapa de bits
  • GoogleMaps GroundOverlay parpadea mis imágenes
  • Android: tamaño de mapa de bits supera 32 bits en DialogFragment
  • Java Java crea mapa de bits a partir del valor hexadecimal
  • Android - Definir el fondo de la aplicación
  • Comparación de imágenes de mapa de bits en Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.