terça-feira, 15 de janeiro de 2013

Recuperar Imagem redimensionada no java

  1. public class ImageUtils {
  2.     private static BufferedImage scale(BufferedImage img, int type, int dimencao, boolean higherQuality) {
  3.         BufferedImage ret = img;
  4.         int w, h;
  5.         if (higherQuality) {
  6.             // Use multi-step technique: start with original size, then
  7.             // scale down in multiple passes with drawImage()
  8.             // until the target size is reached
  9.             w = img.getWidth();
  10.             h = img.getHeight();
  11.         } else {
  12.             // Use one-step technique: scale directly from original
  13.             // size to target size with a single drawImage() call
  14.             w = dimencao;
  15.             h = dimencao;
  16.         }
  17.         Graphics2D graphics = null;
  18.         BufferedImage tmp = null;
  19.         if (higherQuality) {
  20.             if (w >= h) {
  21.                 h = h * dimencao / w;
  22.                 w = dimencao;
  23.             } else {
  24.                 w = w * dimencao / h;
  25.                 h = dimencao;
  26.             }
  27.         }
  28.         tmp = new BufferedImage(w, h, type);
  29.         graphics = tmp.createGraphics();
  30.         graphics.setComposite(AlphaComposite.Src);
  31.         graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  32.         graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  33.         graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  34.         graphics.drawImage(ret, 0, 0, w, h, null);
  35.         graphics.dispose();
  36.         ret = tmp;
  37.         return ret;
  38.     }
  39.     public static byte[] getScaledImage(File file, int dimensao) {
  40.         byte[] result = null;
  41.         try {
  42.             BufferedImage image = ImageIO.read(file);
  43.             BufferedImage thumbs = ImageFileUtils.scale(image, BufferedImage.TYPE_INT_RGB, dimensao, true);
  44.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  45.             ImageIO.write(thumbs, FilenameUtils.getExtension(file.getName()), baos);
  46. //            ImageIO.write(image, FilenameUtils.getExtension(file.getName()), baos);
  47.             result = baos.toByteArray();
  48.         } catch (FileNotFoundException fnfe) {
  49.             logger.debug(fnfe == null ? "Imagem não localizada" : fnfe.getMessage());
  50.         } catch (Exception ex) {
  51.             logger.debug(ex == null ? ">>> erro ao atualizar o Outputstream do response." : ex.getMessage());
  52.         }
  53.         return result;
  54.     }
  55. }

Nenhum comentário:

Postar um comentário