In some situation there might be the need of displaying images received through a byte array (e.g. the image is sent using a socket). The solution is pretty simple. With the following code you can easily create a Component which can display images (e.g. JPEG, GIF) from a byte array. Then you just need to add this component to your GUI.
class ImageComponent extends JPanel { public ImageComponent() {} public ImageComponent (byte[] image) { ByteArrayInputStream bis = new ByteArrayInputStream (image); try { _image = ImageIO.read (bis); } catch (IOException ex){} } //This method replaces the image displayed by the component //with a new one passed in the image byte array. public void updateImage (byte[] image) { ByteArrayInputStream bis = new ByteArrayInputStream (image); try { _image = ImageIO.read (bis); } catch (IOException ex){} repaint(); } public void paint(Graphics g) { g.drawImage(_image, 0, 0, null); } public Dimension getPreferredSize() { if (_image == null) { return new Dimension (320, 240); } else { return new Dimension (_image.getWidth (null), _image.getHeight (null)); } } BufferedImage _image; }
No comments:
Post a Comment