关于将Image转换为byte []并在Java中反转

时间:2012-11-08 05:03:05

标签: java image bytearray

当我将图像转换为byte []并反转时,我遇到了一个问题:

我有2个函数将图像转换为byte [],如下所示

public byte[] extractBytes2 (String ImageName) throws IOException {
    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
    DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();    
    return ( data.getData() );
}

public byte[] extractBytes (String ImageName) throws IOException 
{
    Path path = Paths.get(ImageName);
    byte[] data = Files.readAllBytes(path);
    return data;
}

我将有byte [] byteArray

byteArray = extractBytes2("image/pikachu.png");

byteArray = extractBytes("image/pikachu.png");

当我将byte []转换为Image时,使用

Graphics g = panelMain.getGraphics();
    Graphics2D g2D = (Graphics2D) g;
    try {
        InputStream in = new ByteArrayInputStream(byteArray);
        BufferedImage image = ImageIO.read(in);
        g2D.drawImage(image, 0, 0, GiaoDienChinh.this);
        g2D.setPaint(Color.BLACK);
        panelMain.setOpaque(true);
        panelMain.paintComponents(g2D);
    }
    catch ( Exception e ) {           
    }
    finally {       
    }       

但我只使用byteArray绘制使用函数“extractBytes”而不是“extractBytes2”!!!

任何人都可以解释我如何使用“extractByte2”获得的byteArray绘制图像?

感谢所有支持!

2 个答案:

答案 0 :(得分:7)

让我们从绘画代码开始。

ImageIO.read(in)期待一种有效的图片格式,其中一个可插拔服务提供了解如何阅读并转换为BufferedImage

当你从extractBytes传递过字节时,你只是传回一个代表实际图像文件的字节数组。我跟Image.read(new File("image/pikachu.png"))

一样

但是,从extractBytes2返回的数据缓冲区正在返回图像数据的内部表示,ImageIO可能无法“读取”。

<强>已更新

  

BufferedImage实际上是图像数据的可访问缓冲区   像素,以及它们的RGB颜色。 BufferedImage提供了强大的功能   操纵图像数据的方法。 BufferedImage对象由   两部分是ColorModel对象和Raster对象。

enter image description here

引自here

<强>已更新

我在如何将BufferedImage转换为字节数组的回家路上有这个古怪的想法......

基本想法是使用ImageIO.writeBufferedImage写出来ByteOutputStream ...

public static byte[] extractBytes2(String ImageName) throws IOException {
    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);

    ByteOutputStream bos = null;
    try {
        bos = new ByteOutputStream();
        ImageIO.write(bufferedImage, "png", bos);
    } finally {
        try {
            bos.close();
        } catch (Exception e) {
        }
    }

    return bos == null ? null : bos.getBytes();

}

这是我的测试...

enter image description here

public class TestByteImage {

    public static void main(String[] args) {
        new TestByteImage();
    }

    public static byte[] extractBytes2(String ImageName) throws IOException {
        File imgPath = new File(ImageName);
        BufferedImage bufferedImage = ImageIO.read(imgPath);

        ByteOutputStream bos = null;
        try {
            bos = new ByteOutputStream();
            ImageIO.write(bufferedImage, "png", bos);
        } finally {
            try {
                bos.close();
            } catch (Exception e) {
            }
        }

        return bos == null ? null : bos.getBytes();

    }

    public TestByteImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage original;
        private byte[] byteData;
        private BufferedImage fromBytes;

        public ImagePane() {
            String name = "/path/to/your/image";
            try {
                original = ImageIO.read(new File(name));
                byteData = extractBytes2(name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));

        }

        @Override
        public Dimension getPreferredSize() {
            return original == null ? super.getPreferredSize() : new Dimension(original.getWidth() * 2, original.getHeight());
        }

        protected void drawText(Graphics2D g2d, String text, int x, int width) {
            BufferedImage img = new BufferedImage(width, getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D tmpg = img.createGraphics();
            tmpg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            tmpg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            tmpg.setFont(g2d.getFont());
            tmpg.setColor(Color.RED);
            FontMetrics fm = tmpg.getFontMetrics();
            int xPos = ((width - fm.stringWidth(text)) / 2);
            int yPos = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            tmpg.drawString(text, xPos, yPos);
            tmpg.dispose();

            AffineTransform transform = g2d.getTransform();
            g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-10), x + (x + width) / 2, getHeight() / 2));
            g2d.drawImage(img, x, 0, this);
            g2d.setTransform(transform);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (original != null) {
                g.drawImage(original, 0, 0, this);
                drawText((Graphics2D) g, "Original", 0, original.getWidth());
            }
            if (byteData != null && fromBytes == null) {
                try {
                    fromBytes = ImageIO.read(new ByteInputStream(byteData, byteData.length));
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
            if (fromBytes != null) {
                g.drawImage(fromBytes, getWidth() - fromBytes.getWidth(), 0, this);
                drawText((Graphics2D) g, "From Bytes", getWidth() - fromBytes.getWidth(), fromBytes.getWidth());
            }
        }
    }
}

答案 1 :(得分:0)

使用ImageIo将bufferedImage写入ByteArrayOutputStream,然后调用流的toByteArray方法。BufferedImage to ByteArray