Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Generating thumbnails with transparency
    primarykey
    data
    text
    <p>I'm having problems generating thumbnails of images with an Alpha channel (transparency). The code I use is this:</p> <pre><code>public void saveThumbnail(File file, String imageType) { if (bufferedThumb == null) { return; } if(bufferedImage.getColorModel().hasAlpha()) { logger.debug("Original image has Alpha channel"); } BufferedImage bi = new BufferedImage(bufferedThumb.getWidth(null), bufferedThumb.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.drawImage(bufferedThumb, 0, 0, null); try { ImageIO.write(bi, imageType, file); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Error occured saving thumbnail"); } } </code></pre> <p>However, if I supply for example a GIF image with a transparent background I always end up with a black or colored background.</p> <p>EDIT:</p> <p>This is how it's called from the class using the thumbnail, I missed the two-parameter version of the getThuimbnail()-method the last time:</p> <pre><code>Thumbnail th = new Thumbnail(file.getPath()); th.getThumbnail(100); </code></pre> <p>Added methods used for getting the images:</p> <pre><code>public Thumbnail(String fileName) { try { this.bufferedImage = ImageIO.read(new File(fileName)); } catch (IOException ex) { logger.error("Failed to read image file: " + ex.getMessage()); } } public Image getThumbnail(int size) { int dir = VERTICAL; if (bufferedImage.getHeight() &lt; bufferedImage.getWidth()) { dir = HORIZONTAL; } return getThumbnail(size, dir); } /** * Creates image with specifed max sized to a specified direction. * Will use Image.SCALE_SMOOTH for scaling. * @param size Maximum size * @param dir Direction of maximum size - 0 = vertical, 1 = height. * @return Resized image. */ public Image getThumbnail(int size, int dir) { return getThumbnail(size, dir, Image.SCALE_SMOOTH); } /** * Creates image with specified size. * @param size Maximum size * @param dir Direction of maximum size - 0 = vertical, 1 = height. * @param scale Image.Scale to use for conversion. * @return Resized image. */ public Image getThumbnail(int size, int dir, int scale) { if (dir == HORIZONTAL) { bufferedThumb = bufferedImage.getScaledInstance(size, -1, scale); } else { bufferedThumb = bufferedImage.getScaledInstance(-1, size, scale); } return bufferedThumb; } </code></pre> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload