1.将图片切割为圆形
public static BufferedImage gardenImage(BufferedImage bi1) {
BufferedImage bi2;
bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
BufferedImage.TYPE_INT_RGB);
Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
.getHeight());
Graphics2D g2 = bi2.createGraphics();
g2.setBackground(Color.WHITE);
g2.fill(new Rectangle(bi2.getWidth(), bi2.getHeight()));
g2.setClip(shape);
g2.drawImage(bi1, 0, 0, null);
g2.dispose();
return bi2;
}
2.向图片写入文字
public static Graphics2D create(String str, Image image,int width, int height, Graphics2D g2,int fontSize, Color color ){
BufferedImage bufferedImage = toBufferedImage(image);
g2.drawImage(image, 0, 0, bufferedImage.getWidth() - 25, bufferedImage.getHeight() - 25, null);
Font font = new Font("黑体", Font.BOLD, fontSize);
g2.setFont(font);
g2.setPaint(color);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(str, context);
double y = height;
double ascent = -bounds.getY();
double baseY = y + ascent;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.drawString(str, width, (int) baseY);
return g2;
}
3.将Image 转为 BufferedImage
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
}
if (bimage == null) {
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
4.将字节数组转为image对象
public static Image byteToFile(byte[] bytes) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
Image image = null;
try {
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
image = reader.read(0, param);
} catch (Exception e) {
e.printStackTrace();
} finally {
bis.close();
}
return image;
}
5.将InputStream流转换为byte数组
private byte[] getBytes(InputStream in) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
return swapStream.toByteArray();
}
|