0

我想使用BufferedImage類將圖像文件轉換爲Base64字符串。即使代碼沒有提供任何編譯/運行時錯誤,輸出也不會在控制檯中打印。Java-輸出不打印

的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; 
    } 
} 

如何克服呢?

+0

我_really_想知道爲什麼你認爲'「字符串」'是一個有效的格式名稱。改用'「jpg」'(「bmp」,「png」或任何圖片)。 – Tom

回答

2

問題在於ImageIO.write(image, type, bos);。在你的案例類型是"String",但這很可能不是一個有效的格式。要查看您處置的所有格式,請執行ImageIO.getReaderFormatNames()

如果你可以使用Apache的風景,我建議你嘗試以下到您的文件編碼爲Base64:(fileImageFile類型):

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

我改變了類型「字符串」爲「JPG」,它的工作。謝謝.. – Lucy