Qiita で以下、古い記事を見つけました。
Base64形式で受け取った画像データをBufferedImageに変換
とても参考になり良い記事です。特に、1ピクセルずつ画像を生成する処理は Cool ! です。
Java8 になってからは、Apache Commons Codec の Base64 でデコードしなくても、
java.util.Base64 のデコーダーでなんとかいけるようです。
Qiita の記事を参考にサンプル書いてみました。
1ピクセルずつ画像を生成する処理、ちょっと書き直します。
public static BufferedImage toBufferedImage(byte[] imageBinary) throws IOException{ BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBinary)); int width = img.getWidth(); int height = img.getHeight(); BufferedImage bufImage = new BufferedImage(img.getWidth(), height, BufferedImage.TYPE_INT_RGB); for(int y = 0; y < height; y++){ for(int x = 0 ; x < width; x++){ int c = img.getRGB(x, y); int r = c >> 16 & 0xff; int g = c >> 8 & 0xff; int b = c & 0xff; int rgb = 0xff000000 | r << 16 | g << 8 | b; bufImage.setRGB(x, y, rgb); } } return bufImage; }
Base64 デコードしてこの toBufferedImage を呼び出し BufferedImage を作成します
try(FileInputStream in = new FileInputStream("base64string"); OutputStream out=new FileOutputStream("sample.png"); ByteArrayOutputStream bo = new ByteArrayOutputStream();){ byte[] b = new byte[1024]; int len; while((len = in.read(b, 0, b.length)) > 0){ bo.write(b, 0, len); } BufferedImage bimage = toBufferedImage(Base64.getDecoder().decode(bo.toString())); ImageIO.write(bimage, "png", out); }catch(Exception e){ e.printStackTrace(); }
先日書いた、
Chart.js 図全体背景色、グラフエリア背景色、イメージダウンロードの問題を解決する - Oboe吹きプログラマの黙示録
でIEでできなかったダウンロードも、Base64 エンコードしたものを、FORMーPOST送信で
サーバに送って、サーバ側で上の処理の結果の画像をストリーム出力すれば
ダウンロードできますね。