Java正常图片转为缩略图

it2023-01-05  65

public static InputStream getInputStream(String destUrl) { InputStream inputStream = null; URLConnection urlConnection = null; URL url = null; try { url = new URL(destUrl); urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return inputStream; } public static byte[] toByteArray(InputStream is) throws IOException { ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int ch; while ((ch = is.read(buffer)) != -1) { bytestream.write(buffer, 0, ch); } byte data[] = bytestream.toByteArray(); bytestream.close(); return data; } /** * 获取缩略图(返回类型可以自己修改,这里返回类型为MultipartFile) */ public MultipartFile zoomImage(String fileName) throws IOException { Map<String, Boolean> map = new HashMap<String, Boolean>(); for (String s : new String[]{"jpg", "png", "gif"}) { map.put(s, true); } MultipartFile multipartFile = null; BufferedImage bufferedImage = null; File file = new File(fileName); int toWidth = 400, toHeight = 300; BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); try { if (file.length() != 0 && map.get(file.getName().split("\\.")[file.getName().split("\\.").length - 1]) != null) { //文件大小不为空,并且文件有后缀名 bufferedImage = ImageIO.read(file); result.getGraphics().drawImage(bufferedImage.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); //BufferedImage转为InputStream ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(result, "jpg", imOut); InputStream inputStream = new ByteArrayInputStream(bs.toByteArray()); try { multipartFile = new MockMultipartFile("file", new Date().getTime() + ".png", "image/png", toByteArray(inputStream)); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { multipartFile = null; } return multipartFile; }
最新回复(0)