【问题标题】:java image data inputstreamjava图像数据输入流
【发布时间】:2012-04-20 01:25:50
【问题描述】:

下面的方法将 InputStream 中的数据作为字符串返回,该字符串将使用 StringBuilder 构造

String getBytes(InputStream is) throws IOException{
   StringBuilder sb = new StringBuilder();
   int ch;
   while ((ch = is.read()) != -1) sb.append((char)ch);
   is.close();
   return sb.toString();
}

但此方法不适用于图像数据。最好的解决方案是构建类似的方法,但返回字节 [] 而不是字符串。谁能告诉我怎么做?

【问题讨论】:

    标签: java image byte inputstream


    【解决方案1】:

    希望这是您正在寻找的。我将此函数用于我的 Imgur 应用程序,该应用程序需要 ByteArray 形式的图像。

    static File imgFile;
    static ByteArrayOutputStream imgStream = new ByteArrayOutputStream();
    
    public static void bufferImage() {
            try {
                    BufferedImage bufImg = ImageIO.read(imgFile);
                    ImageIO.write(bufImg, getExtension(imgFile), imgStream);
             } catch (IOException ex) {
                    System.out.println("Error buffering image");
               }   
        }
    

    如果你愿意,我也可以提供 getExtension 函数。

    【讨论】:

    • +1 我看着那个问题并想,“哇,从哪里开始?”。幸运的是,您直接进入“如何解决”。 :)
    • 我刚刚使用了 IOUtils.toByteArray(...)。不幸的是我得到了这个错误:线程“pool-1-thread-1”java.lang.ExceptionInInitializerError中的异常。我不知道为什么
    猜你喜欢
    • 2011-06-06
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多