Google Cloud Storageに保存した画像をリサイズして応答する方法
最近はスマートフォンで撮影できる画像の解像度が巨大化してるので、そのままを表示すると遅くなってしまう。
そこで、リクエストパラメータにwidthを追加して、任意のサイズで表示できるようにした。
ここではblobKeyを元にBlobInfoを求めてるけど、ファイル名を元にしたい場合は makeImageFromFilename()でも可能。
≫ ImagesServiceFactory(Google App Engine API for Java) | Java の App Engine スタンダード環境 | Google Cloud
String key = request.getParameter("key"); String width = request.getParameter("width"); int w = 1024; try { w = Integer.parseInt(width); } catch (Exception e) {} BlobKey blobKey = new BlobKey(key); BlobInfo info = new BlobInfoFactory().loadBlobInfo(blobKey); Image image = ImagesServiceFactory.makeImageFromBlob(blobKey); Transform tf = ImagesServiceFactory.makeResize(w, w); Image resized = ImagesServiceFactory.getImagesService().applyTransform(tf, image); byte[] data = resized.getImageData(); String contentType = info.getContentType(); if (contentType == null || contentType.isEmpty()) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } response.setContentLength(data.length); ServletOutputStream os = response.getOutputStream(); os.write(data);