java - 关于在 Java 中将 Image 转换为 byte[] 和反转

标签 java image arrays

我在将图像转换为 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[] 转换为我使用的图像时

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

感谢大家的支持!

最佳答案

让我们从绘制代码开始。

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

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

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

已更新

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.

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

关于java - 关于在 Java 中将 Image 转换为 byte[] 和反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282740/

相关文章:

java - Android BroadcastReceiver 不更新小部件

database - 如何使用模型优先方法使用 EF 4.0 将图像存储在数据库中。 MVC2

c++ - gcc 4.8.2 和 gcc 4.9.0 在数组大小时的行为差异

java - JVM 在调用停止之前允许关闭 Hook 运行多长时间?

java - 从 java 代码更改图像布局和位置

java - 具有 2 个外键选项的 Hibernate 实体

image - SVG 图像作为页面背景 xamarin

asp.net - 如何在 ASP.NET 中设置图片作为背景?

javascript - 如何在 Angular 中使用 splice 从列表中删除项目?

javascript - 为什么球在我的 pong JavaScript Canvas 游戏中不能完全弹跳?