直接上代码把
/**
* 图片设置圆角
* @param srcImage
* @param radius
* @param border
* @param padding
* @return
* @throws IOException
*/
@SuppressWarnings("all")
public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding) throws IOException{
int width = srcImage.getWidth();
int height = srcImage.getHeight();
int canvasWidth = width + padding * 2;
int canvasHeight = height + padding * 2;
BufferedImage image = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, srcImage.getWidth(),
srcImage.getHeight());
Graphics2D g2 = image.createGraphics();
image = g2.getDeviceConfiguration().createCompatibleImage(srcImage.getWidth(), srcImage.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,srcImage.getWidth(), srcImage.getHeight(), radius, radius);
g2.setComposite(AlphaComposite.SrcIn);
g2.drawImage(srcImage, 0, 0, srcImage.getWidth(), srcImage.getHeight(), null);
if(border !=0){
// gs.setColor(Color.GRAY);
g2.setColor(Color.GRAY);
g2.setStroke(new BasicStroke(border));
g2.drawRoundRect(padding, padding, canvasWidth * padding, canvasHeight * padding, radius, radius);
}
g2.dispose();
return image;
}
调整尺寸
/**
* 重调图片尺寸
*
* @param input
* a {@link java.io.InputStream} object.
* @param output
* a {@link java.io.OutputStream} object.
* @param width
* a int.
* @param height
* a int.
* @param maxWidth
* a int.
* @param maxHeight
* a int.
*/
@SuppressWarnings("all" )
public static BufferedImage resize(BufferedImage img, int width, int height ) throws Exception {
try {
boolean hasNotAlpha = !img.getColorModel().hasAlpha();
double w = img.getWidth(null);
double h = img.getHeight(null);
int toWidth;
int toHeight;
double rate = w / h;
if (width > 0 && height > 0) {
rate = ((double) width) / ((double) height);
toWidth = width;
toHeight = height;
} else if (width > 0) {
toWidth = width;
toHeight = (int) (toWidth / rate);
} else if (height > 0) {
toHeight = height;
toWidth = (int) (toHeight * rate);
} else {
toWidth = ((Number) w).intValue();
toHeight = ((Number) h).intValue();
}
BufferedImage tag = new BufferedImage(toWidth, toHeight, hasNotAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
// Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
tag.getGraphics().drawImage(img.getScaledInstance(toWidth, toHeight, Image.SCALE_SMOOTH), 0, 0, null);
return tag;
// ImageIO.write(tag, hasNotAlpha ? "jpg" : "png", output);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
} finally {
}
}