una ruta redimensionar poner manejo insertar imagenes imagen escalar cargar abrir java gwt image-scaling

ruta - redimensionar imagen java



Escalar una imagen en GWT (7)

Al cambiar el tamaño de un widget de Image en GWT, se cambia el tamaño del elemento de imagen, pero no se vuelve a escalar la imagen en la pantalla. Por lo tanto, lo siguiente no funcionará:

Image image = new Image(myImageResource); image.setHeight(newHeight); image.setWidth(newWidth); image.setPixelSize(newWidth, newHeight);

Esto se debe a que GWT implementa su widget de Image configurando la background-image de background-image del elemento HTML <img... /> como la imagen, usando CSS.

¿Cómo se obtiene la imagen real para cambiar el tamaño?



De todas mis pruebas, SafeURI funciona solo si tienes UNA imagen en tu paquete ... ¡De nada sirve usarla porque tienes un cache.png de Bundle, así que no optimizas nada!


Escribí una clase que acepta un objeto ImageResource y puede establecer el tamaño de píxel deseado de la imagen. Utiliza CSS background-Position y CSS background-size para alcanzar el objetivo:

El código fuente de la clase ScalableImage es:

package de.tu_freiberg.informatik.vonwenckstern.client; // class is written by Michael von Wenckstern, and is also used in ist diploma Thesis // (this is only for my super visor, that he does not think I copied it from // without mention the source) - this class is free to use for every body import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Image; public class ScalableImage extends Image { private int width; private int height; private ImageResource res; public ScalableImage(ImageResource res, int width, int height) { this.setUrl(res.getSafeUri()); this.res = res; this.width = width; this.height = height; } @Override public void onLoad() { int widthOfBigImage = this.getOffsetWidth(); int heightOfBigImage = this.getOffsetHeight(); double scaleX = width / res.getWidth(); double scaleY = height / res.getHeight(); this.setResource(res); DOM.setStyleAttribute(getElement(), "backgroundPosition", Integer.toString((int) (res.getLeft() * -1 * scaleX))+"px "+ Integer.toString((int) (res.getTop() * -1 * scaleY))+"px "); DOM.setStyleAttribute(getElement(), "backgroundSize", Integer.toString((int) (widthOfBigImage * scaleX))+"px "+ Integer.toString((int) (heightOfBigImage * scaleY))+"px "); this.setPixelSize((int) (res.getWidth()* scaleX), (int) (res.getHeight() * scaleY)); } }

Puedes usar esta clase como sigue:

rootPanel.add(new ScalableImage(Images.Util.getImages().img0(), 60, 60));

Si usa esta clase junto con un PushButton, entonces debe agregar PushButton al RootPanel, porque de lo contrario no se llama a la función onLoad (). Un código fuente de ejemplo se vería así:

for(ImageResource imRes: latexIconsClientBundle) { ScalableImage im = new ScalableImage(imRes, 60, 60); RootPanel.get().add(im); // PushButton class does not fire onAttach event, so we need to attach the image to the RootPanel PushButton btn = new PushButton(im); btn.setPixelSize(60, 60); if(++col > 9) { row++; col = 0; } this.setWidget(row, col, btn); }



Si queremos hacer lo mismo en UIbinder. De un recurso externo, entonces:

Por ejemplo, tenemos en recursos

@Source("images/logo.png") ImageResource getLogo();

En la plantilla de UiBinder, declare el elemento <ui:with> :

<ui:with field=''res'' type=''com.myapp.client.Resources''/>

y por debajo:

<g:Image url=''{res.getLogo.getSafeUri.asString}'' pixelSize="Width, Height" />

en versiones anteriores de GWT:

<g:Image url=''{res.getLogo.getURL}'' pixelSize="Width, Height" />

pero ahora - Obsoleto.

No utilice:

<g:Image resource=''{res.getLogo}'' pixelSize="Width, Height" />

porque no escala las imágenes


Vi esta entrada de blog , que resuelve el problema utilizando GWT DataResource en lugar de ImageResource. Resulta que la misma técnica funcionará realmente con ImageResource, si la usas de la siguiente manera:

Image image = new Image(myImageResource.getURL()); image.setPixelSize(getLength(), getHeight());

Para mantener la relación de aspecto, calcúlela como sigue:

Image image = new Image(myImageResource.getURL()); image.setPixelSize(newWidth, myImageResource.getHeight() * newWidth / myImageResource.getWidth());

A partir de GWT 2.4, use (ver here ):

Image image = new Image(myImageResource.getSafeUri()); image.setPixelSize(newWidth, myImageResource.getHeight() * newWidth / myImageResource.getWidth());


mi solución final fue agregar un controlador de carga en la imagen para cambiar su tamaño de acuerdo con las dimensiones de la imagen cargada (es decir, respetando la relación).

image.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { Element element = event.getRelativeElement(); if (element == image.getElement()) { int originalHeight = image.getOffsetHeight(); int originalWidth = image.getOffsetWidth(); if (originalHeight > originalWidth) { image.setHeight(MAX_IMAGE_HEIGHT + "px"); } else { image.setWidth(MAX_IMAGE_WIDTH + "px"); } } } });

donde MAX_IMAGE_WIDTH y MAX_IMAGE_HEIGHT son constantes que determinan el tamaño máximo permitido de la imagen.