【问题标题】:Java- Output not printingJava-输出不打印
【发布时间】:2016-05-05 10:04:47
【问题描述】:

我正在尝试使用 BufferedImage 类将图像文件转换为 Base64 字符串。即使代码没有给出任何编译/运行时错误,输出也不会打印在控制台中。

Eclipse IDE 代码:

public class BufferImage {

public static void main(String args[]) {
try 
{
    BufferedImage img = null;
    img = ImageIO.read(new File("image.jpg")); // eventually C:\\ImageTest\\pic2.jpg
    String image_string = encodeToString(img, "string");
    System.out.println(image_string);
} 
catch (IOException e) 
{
    e.printStackTrace();
}
}

public static String encodeToString(BufferedImage image, String type) 
{
    String base64String = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
    ImageIO.write(image, type, bos);
    byte[] imageBytes = bos.toByteArray();
    BASE64Encoder encoder = new BASE64Encoder();
    base64String = encoder.encode(imageBytes);
    bos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return base64String;
    }
}

如何克服这个问题?

【问题讨论】:

  • 真的想知道为什么你认为"string" 是一个有效的格式名称。请改用"jpg"(“bmp”、“png”或任何您的图片)。

标签: java file-io bufferedimage javax.imageio bytearrayoutputstream


【解决方案1】:

问题出在ImageIO.write(image, type, bos);。在您的情况下,类型是 "String",但这很可能不是有效的格式。要查看您可以使用的所有格式,请执行ImageIO.getReaderFormatNames()

如果您可以使用 Apache Commons,我建议您尝试以下方法将您的文件编码为 Base64:(fileImage 的类型为 File):

byte[] imageBytes = Base64.encode(FileUtils.readFileToByteArray(fileImage)); 
String base64String = new String(imageBytes);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多