首先要理解 exif orientation 概念。非常重要,这个Orientation值提供了想要正常观看图像时应该旋转的方式。
例如 iPhone 正常观看是 Home 在右,横拍
Java 自动翻转处理代码,借助 thumbnailator 库实现:
pom.xml
<dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>[0.4, 0.5)</version> </dependency>
核心代码:
public static BufferedImage getImageFromUrl(String url) throws Exception { try { HttpClient client = HttpClientUtil.getHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { EntityUtils.consumeQuietly(response.getEntity()); } // return ImageIO.read(response.getEntity().getContent()); // auto rotate image orientation return Thumbnails.of(response.getEntity().getContent()).scale(1).asBufferedImage(); } catch (IOException e) { throw new IOException("getImageFromUrl Error"); } }