【问题标题】:About convert Image to byte[] and reverse in Java关于将 Image 转换为 byte[] 并在 Java 中反转
【发布时间】:2012-10-28 06:39:42
【问题描述】:

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

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

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 绘制图像?

感谢大家的支持!

【问题讨论】:

  • 我其实不明白这个问题:是方法extractBytes2 不起作用还是没有被调用或者byteArray 在你绘制图像时总是持有extractBytes 的结果?

标签: java image bytearray


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    让我们从绘制代码开始。

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

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

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

    更新

    BufferedImage 是一个可访问的图像数据缓冲区,本质上是 像素,以及它们的 RGB 颜色。 BufferedImage 提供了强大的 操作图像数据的方法。 BufferedImage 对象由 由 ColorModel 对象和 Raster 对象两部分组成。

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

    这是我的测试...

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

    【讨论】:

    • 谢谢我明白了。但是有什么方法可以使用extractBytes2 的byteArray 来绘制图像?
    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 2012-08-28
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多