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 Commonsのを使用することができる場合、私はあなたがBase64でのあなたのファイルをエンコードするために、以下しようと提案する:(fileImageはタイプFileのですが):

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

"String"を "jpg"に変更しました。ありがとうございます.. – Lucy

関連する問題