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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13282740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:06:58  来源:igfitidea点击:

About convert Image to byte[] and reverse in Java

javaimagebytearray

提问by dleviathan

i have one problem when i convert image to byte[] and reverse:

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

I have 2 function convert image to byte[] as follow

我有 2 个函数将图像转换为字节 [] 如下

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() );
}

and

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

I will have byte[] byteArray

我将有 byte[] byteArray

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

or

或者

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

when i convert byte[] to Image i use

当我将 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 {       
    }       

but i only draw with byteArray use function "extractBytes" not with "extractBytes2" !!!

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

Anyone can explain me how i can draw image with byteArray which got from "extractByte2"?

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

Thanks for all support!

感谢大家的支持!

回答by MadProgrammer

Let's start with the paint code.

让我们从绘制代码开始。

ImageIO.read(in)is expecting a valid image format that one of it's pluggable service provides knows how to read and convert to a BufferedImage.

ImageIO.read(in)期待一种有效的图像格式,它的一个可插拔服务提供知道如何读取和转换为BufferedImage.

When you pass the byes from extractBytes, you're simply passing back an array of bytes that represents the actual image file. I'd be the same as saying Image.read(new File("image/pikachu.png"))

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

However, the data buffer returned from your extractBytes2is returning a internal representation of the image data, which may not be "readable" by ImageIO.

但是,从您extractBytes2返回的数据缓冲区正在返回图像数据的内部表示,它可能无法被ImageIO.

UPDATED

更新

A BufferedImage is an accessible buffer of image data, essentially pixels, and their RGB colors. The BufferedImage provides a powerful way to manipulate the Image data. A BufferedImage object is made up of two parts a ColorModel object and a Raster object.

BufferedImage 是图像数据(本质上是像素)及其 RGB 颜色的可访问缓冲区。BufferedImage 提供了一种强大的方法来操作 Image 数据。BufferedImage 对象由两部分组成:ColorModel 对象和 Raster 对象。

enter image description here

在此处输入图片说明

Referenced from here

这里引用

UPDATED

更新

I had this wacky idea on the way home of how to convert a BufferedImageto a byte array...

在如何将 a 转换BufferedImage为字节数组的路上,我有一个古怪的想法......

The basic idea is to use ImageIO.writeto write out the BufferedImageto a ByteOutputStream...

其基本思想是用ImageIO.write在写出来BufferedImageByteOutputStream......

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();

}

Here's my test...

这是我的测试...

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());
            }
        }
    }
}