Java ImageIcon imageToBytes(ImageIcon icon)

Here you can find the source of imageToBytes(ImageIcon icon)

Description

image To Bytes

License

Open Source License

Declaration

public static byte[] imageToBytes(ImageIcon icon) throws IOException 

Method Source Code


//package com.java2s;
/*//from  ww  w  . j a  v a2s.co m
 * Copyright (C) 2010 Francisco Jos? Morero Peyrona. All Rights Reserved.
 *
 * This file is part of Tapas project: http://code.google.com/p/tapas-tpv/
 *
 * GNU Classpath is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the free
 * Software Foundation; either version 3, or (at your option) any later version.
 *
 * Tapas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Tapas; see the file COPYING.  If not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
    public static byte[] imageToBytes(ImageIcon icon) throws IOException {
        if (icon == null) {
            return null;
        }

        Image img = icon.getImage();

        if (img.getWidth(null) < 1 && img.getHeight(null) < 1) {
            return null;
        }

        BufferedImage image = getBufferedImageFromImage(img);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(image, "png", baos);

        return baos.toByteArray();
    }

    private static BufferedImage getBufferedImageFromImage(Image img) {
        // Crea un objeto BufferedImage con el ancho y alto de la Image
        BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();

        return bufferedImage;
    }
}

Related

  1. getThumbImage(ImageIcon myLoadedImageIcon, int thumbHeight, int thumbWidth)
  2. getThumbnail(ImageIcon src, int maxWidth)
  3. grabRGB(ImageIcon icon)
  4. iconDefaultSize(ImageIcon imag)
  5. imageFlip(int w, int h, ImageIcon... icons)
  6. imageWithBackground(ImageIcon icon, Color colorBg)
  7. initImageIcon(Class cl)
  8. isValidImg(ImageIcon img)
  9. loadJavaInternal(ImageIcon r, Dimension d, boolean noStretch)