【问题标题】:Convert a byte[] to a BufferedImage将 byte[] 转换为 BufferedImage
【发布时间】:2017-11-21 05:25:15
【问题描述】:

我在将 byte[] 转换为 BufferedImage 时遇到问题。我知道有很多帖子和问题答案,但我就是不明白为什么我的代码是错误的。 (错误:线程“main”java.lang.IllegalArgumentException 中的异常:image == null!)

谢谢!

try {
        String hex = "57656c636f6d652c206d7920667269656e642e";
        byte[] im = DatatypeConverter.parseHexBinary(hex);
        InputStream in = new ByteArrayInputStream(im);
        BufferedImage bImageFromConvert = ImageIO.read(in);
        ImageIO.write(bImageFromConvert, "jpg", new File("c:/welcome.jpg"));
    } catch (Exception ex) {
    }

【问题讨论】:

  • 好的,所以我解码了十六进制字符串,它说“欢迎,我的朋友。” ImageIO.read() 读取 JPG 和 PNG 等文件。你期望它对一串 ascii 做什么?
  • 要将文本转换为图像,您需要创建所需大小的缓冲图像,根据需要填充背景,设置颜色,设置字体,然后在其上绘制字符串。你不能只用几行代码将文本变成图像(反正不是用 java 标准库)
  • 你看不出你的代码为什么错了?你怎么能想象你的代码是正确的?
  • 另外,如果您的十六进制字符串包含 JPEG,则无需将其解码为 BufferedImage 并再次编码。只需将解析后的字节 (im) 直接写入文件即可。

标签: java byte bufferedimage


【解决方案1】:

如果我理解正确,你只需要使用

File newfile = new File("c:/welcome.jpg"); 
newfile.exists();

检查新文件是否存在。

【讨论】:

  • 它无法写入文件,因为它无法转换“欢迎,我的朋友”。成图像。 ImageIO.read() 会这样做的前提是错误的
【解决方案2】:

好的。我按照slipperyseal 所说的做了并且工作了。谢谢。代码如下。

try {
        Font font = new Font("Arial", 0, 32);
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        FontMetrics fm = img.getGraphics().getFontMetrics(font);
        int width = fm.stringWidth("Welcome, my friend.");
        int height = fm.getHeight();
        int padding = 7;

        BufferedImage bgImage = new BufferedImage(width+padding*2, height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D drawer = bgImage.createGraphics() ;
        drawer.setBackground(Color.white);
        drawer.clearRect(0,0,(int)width+padding*2,(int)height);
        drawer.setColor(Color.black);
        drawer.setFont(font);
        drawer.drawString("Welcome, my friend.", padding, height-padding);

        ImageIO.write(bgImage, "png", new File("c:/welcome.png"));

    } catch (IOException e) {
            System.out.println(e.getMessage());
    }

该代码有问题吗?就像不好的做法一样,...

【讨论】:

  • 这可能有效,但我看不出它与问题有何关系......这是“如何创建图像,为其绘制字符串并将其另存为”的答案JPEG?”...
猜你喜欢
  • 2015-05-23
  • 2012-05-01
  • 2020-02-16
  • 2011-06-08
  • 2014-07-21
  • 1970-01-01
  • 2012-11-30
  • 2013-08-10
  • 2013-02-09
相关资源
最近更新 更多