Spring Bootで画像を縮小して表示
画像を縮小する
そもそも画像制御とかプログラムでほとんど書かないけどね
実装
Image01Controller.java
package com.example.controller; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.core.io.ResourceLoader; import javax.imageio.ImageIO; @RestController public class Image01Controller { @Autowired ResourceLoader resourceLoader; private int c; @ResponseBody @RequestMapping(value = "/getImageReducing/{id}", method = {RequestMethod.GET }) public HttpEntity<byte[]> getImageReducing(@PathVariable String id) throws IOException { // リソースファイルを読み込み Resource resource = resourceLoader.getResource("classpath:" + "/static/image/" + id + ".jpg"); InputStream image = resource.getInputStream(); // BufferedImageへ設定 BufferedImage bufferedImage1 = ImageIO.read(image); BufferedImage bufferedImage2 = null; // 変換情報を設定 int width = 300; int height = 250; Image image1 = bufferedImage1.getScaledInstance(width, height, Image.SCALE_DEFAULT); bufferedImage2 = new BufferedImage(image1.getWidth(null), image1.getHeight(null), BufferedImage.TYPE_INT_RGB); // 縮小処理 Graphics graphics2 = null; try { graphics2 = bufferedImage2.getGraphics(); int x = 0; int y = 0; graphics2.drawImage(bufferedImage1, x, y, width, height, null); } finally { graphics2.dispose(); } // byteへ変換 ByteArrayOutputStream bout = new ByteArrayOutputStream(); ImageIO.write(bufferedImage2, "jpg", bout); byte[] b = bout.toByteArray(); // レスポンスデータとして返却 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentLength(b.length); return new HttpEntity<byte[]>(b, headers); } }