2 Replies Latest reply: Mar 3, 2011 5:18 PM by morgalr RSS

    Resizing a jpg picture sometimes fails.

    787016
      I use this code to resize a jpg picture. Sometimes i get the resized image but sometimes instead of the resized image i get a black image.
      It is a web application so this code is within a servlet.
      Any hints?

      +protected void doGet(......){+

      +........+
      +........+

      response.setContentType(CONTENT_TYPE_IMAGE_JPG);

      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder
      +(response.getOutputStream());+
      encoder.encode(resizeImage(imageBytes));
      +}+

      +private BufferedImage resizeImage(byte [] imageBytes) {+

      +try {+

      InputStream inputStream =  new ByteArrayInputStream(imageBytes);
      BufferedImage bufferedImage = ImageIO.read(inputStream);

      ++return resize(bufferedImage, 250, 300);+


      +}catch (Exception e) {+
      throw new RuntimeException(e);
      +}+

      +}private BufferedImage resize(BufferedImage img, int newW, int newH) {+


      int w = img.getWidth();

      int h = img.getHeight();

      BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());

      Graphics2D g = dimg.createGraphics();

      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

      g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);

      g.dispose();

      return dimg;

      +}+
        • 1. Re: Resizing a jpg picture sometimes fails.
          793415
          784013 wrote:
          I use this code to resize a jpg picture. Sometimes i get the resized image but sometimes instead of the resized image i get a black image.
          It is a web application so this code is within a servlet.
          Any hints?
          <li> Use code tags as mentioned on the 'sticky post' at the top of the forum listing.
          <li> For better help sooner, post an SSCCE (http://pscode.org/sscce.html).
          <li> Clarify whether 'sometimes' means that some images always fail, while others always work, or alternately if this 'black image' effect can happen for images that resize successfully at other times.
          • 2. Re: Resizing a jpg picture sometimes fails.
            morgalr
            This looks a little hinky: I've never had this work:
              BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
            should be
              BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
            Also if for some reason your img.getType does not work--you'll get a black screen. I seem to remember back amoungst the cobwebs of my mind that GIF formats will sometimes produce strange results. Check your getType return value to see if it is a valid type or not.