import xyz.laremehpe.FileUtil.FileChooser; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Date; public class roundImg { /**图片圆角处理,背景透明化 * @param srcImageFile 原图片 * @param result 处理后图片 * @param type 图片格式 * @param cornerRadius 720为圆角 */ public static void main(String[] args) { new roundImg(50);//圆角度数 } public roundImg(int radius){ String src = FileChooser(0); String affix = src.substring(src.length()-3); if("".equals(src))return; String replacement = "\\\\"+new Date().getTime()+"."+affix; String res = src.replaceAll("\\\\[a-zA-Z0-9\u4e00-\u9fa5]*\\."+affix,replacement); makeRoundedCorner(new File(src),new File(res),affix,radius); }
public String FileChooser(int type) {// 1 -> directory 0 -> file JFileChooser jc = new JFileChooser(); jc.setFileSelectionMode(type); jc.setDialogTitle("Select file"); jc.setCurrentDirectory(FileSystemView.getFileSystemView().getHomeDirectory());// set default directory as jc.showOpenDialog(null); return jc.getSelectedFile().toString(); }
public void makeRoundedCorner(File srcImageFile, File result, String type, int cornerRadius) { try { BufferedImage bi1 = ImageIO.read(srcImageFile); // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_ARGB); Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1 .getHeight()); Graphics2D g2 = image.createGraphics(); image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT); g2 = image.createGraphics(); g2.setComposite(AlphaComposite.Clear); g2.fill(new Rectangle(image.getWidth(), image.getHeight())); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f)); g2.setClip(shape); // 使用 setRenderingHint 设置抗锯齿 g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.fillRoundRect(0, 0,bi1.getWidth(), bi1.getHeight(), cornerRadius, cornerRadius); g2.setComposite(AlphaComposite.SrcIn); g2.drawImage(bi1, 0, 0, bi1.getWidth(), bi1.getHeight(), null); g2.dispose(); ImageIO.write(image, type, result); } catch (Exception e) { // TODO: handle exception } } }
标签:圆角,java,g2,image,String,import,new,图片,bi1 From: https://www.cnblogs.com/laremehpe/p/16895865.html