Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Struts
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Tim Cooke
paul wheaton
Jeanne Boyarsky
Ron McLeod
Sheriffs:
Paul Clapham
Liutauras Vilda
Devaka Cooray
Saloon Keepers:
Tim Holloway
Roland Mueller
Bartenders:
Forum:
Struts
Displaying images and thumbnails directly from database
Chris Boldon
Ranch Hand
Posts: 190
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
I couldn't find many good examples on displaying images directly from the database (especially related to resizing), so I figured I'd post some code snips here to save people in the future some time:
ImageTools.java
public class ImageTools { private static final Logger LOG = Logger.getLogger(ImageTools.class); public Image createThumbnail(Image image) { BufferedImage bufferedImage = toBufferedImage(image); BufferedImage bufThumb = createThumbnail(bufferedImage); Image thumbImage = toImage(bufThumb); return thumbImage; } private static BufferedImage toBufferedImage(Image image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); // Determine if the image has transparent pixels; for this method's // implementation, see e661 Determining If an Image Has Transparent // Pixels boolean hasAlpha = hasAlpha(image); // Create a buffered image with a format that's compatible with the // screen BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.BITMASK; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(image.getWidth(null), image .getHeight(null), transparency); } catch (HeadlessException e) { LOG.error("This system does not have a screen", e); } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage(image.getWidth(null), image .getHeight(null), type); } // Copy image to buffered image Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; } private static boolean hasAlpha(Image image) { // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; return bimage.getColorModel().hasAlpha(); } // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { LOG.error(e); } // Get the image's color model ColorModel cm = pg.getColorModel(); return cm.hasAlpha(); } private Image toImage(BufferedImage bufferedImage) { return Toolkit.getDefaultToolkit().createImage( bufferedImage.getSource()); } private BufferedImage createThumbnail(BufferedImage orig) { final int WIDTH = 75; final int HEIGHT = 75; AffineTransform at; BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); // g2.setPaint(bgColor); g2.fillRect(0, 0, WIDTH, HEIGHT); // scale to fit double xScale = (double) WIDTH / orig.getWidth(); double yScale = (double) HEIGHT / orig.getHeight(); double scale = Math.min(xScale, yScale); // center thumbnail image double x = (WIDTH - orig.getWidth() * scale) / 2; double y = (HEIGHT - orig.getHeight() * scale) / 2; at = AffineTransform.getTranslateInstance(x, y); at.scale(scale, scale); g2.drawRenderedImage(orig, at); g2.dispose(); return image; } }
DisplayImageAction.java:
public class DisplayImageAction extends Action { private static final Logger LOG = Logger .getLogger(DisplayImageAction.class); private ListerFacade listerFacade; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { LOG.debug("Creating image from Blob"); String listingId = request.getParameter("listing"); Blob imgBlob = listerFacade.getListingById(Integer.valueOf(listingId)) .getFile().getFileBin(); try { byte[] picBytes = imgBlob.getBytes(1, (int) imgBlob.length()); response.setContentType("image/jpeg"); response.getOutputStream().write(picBytes); } catch (SQLException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } return null; }
DisplayThumbnailAction:
public class DisplayThumbnailAction extends Action { private static final Logger LOG = Logger .getLogger(DisplayThumbnailAction.class); ImageTools imageTools = new ImageTools(); private ListerFacade listerFacade; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { LOG.debug("Creating thumbnail from Blob"); String listingId = request.getParameter("listing"); Blob imgBlob = listerFacade.getListingById(Integer.valueOf(listingId)) .getFile().getFileBin(); try { byte[] picBytes = imgBlob.getBytes(1, (int) imgBlob.length()); Image image = Toolkit.getDefaultToolkit().createImage(picBytes); Image thumbImage = imageTools.createThumbnail(image); byte[] thumbBytes = imageToByteArray(thumbImage); response.setContentType("image/jpeg"); response.getOutputStream().write(thumbBytes); } catch (SQLException e) { LOG.error(e); } catch (IOException e) { LOG.error(e); } return null; } public static byte[] imageToByteArray(Image image) { try { MediaTracker tracker = new MediaTracker(new Container()); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } BufferedImage bufferedImage = new BufferedImage(image .getWidth(null), image.getHeight(null), 1); Graphics gc = bufferedImage.createGraphics(); gc.drawImage(image, 0, 0, null); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpeg", bos); return bos.toByteArray(); } catch (IOException e) { LOG.error(e); } return null; } }
Brent Sterling
Ranch Hand
Posts: 948
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Thanks for posting...could be useful. Does this code use just standard
Java
libraries for the image manipulation?
- Brent
Chris Boldon
Ranch Hand
Posts: 190
posted 17 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Yes, it is standard java libraries.
Well don't expect me to do the dishes! This ad has been cleaned for your convenience:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
how to pass the image from servlet to jsp
lagging on loading image
Image to BufferedImage converter
works on WinXP jdk 1.6 but not Linux jdk 1.5
Need help ImageToCode
More...