本文主要是介绍java ImageIO.write图片上传变色及背景变黑解决,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java ImageIO.write图片上传变色及背景变黑解决
public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");response.addHeader("Cache-Control", "post-check=0, pre-check=0");response.setHeader("Pragma", "no-cache");response.setContentType("image/jpeg");String uri = request.getRequestURI();String imgPath = uri.replace("/ofc/rest/img", "");File image = new File(imgPath);BufferedImage bi = ImageIO.read(image);BufferedImage newBi = resizeImagePng(bi.getWidth(), bi.getHeight(),bi);Graphics2D g2d = newBi.createGraphics();g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));ServletOutputStream out = response.getOutputStream();g2d.drawImage(newBi,0,0,null);ImageIO.write(newBi,"png", out);//ImageIO.write(bi, "jpg", out);//saveAs(bi,"jpg", out);}
public static BufferedImage resizeImagePng(int x, int y, BufferedImage bfi) {BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);bufferedImage.getGraphics().drawImage(bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);return bufferedImage;}
public static void saveAs(BufferedImage image, String formatName, ServletOutputStream outFile) throws IOException {if (formatName.equalsIgnoreCase("jpg") || formatName.equalsIgnoreCase("jpeg")) {BufferedImage tag = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_BGR);Graphics g = tag.getGraphics();// Graphics2D gg=tag.createGraphics();
// tag = gg.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(),Transparency.TRANSLUCENT);
// gg.dispose();
// gg = tag.createGraphics();
// gg.drawImage(image, 0, 0,null);g.drawImage(image, 0, 0,image.getWidth(), image.getHeight(),image.getGraphics().getColor(), null); // 绘制缩小后的图g.dispose();image = tag;}ImageIO.write(image, formatName, outFile);}
这篇关于java ImageIO.write图片上传变色及背景变黑解决的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!