因为我发现用别的格式的图片会有时候出现bug 所以我干脆直接写了个转换成.png格式的方法
public final class ImageUtils {
public ImageUtils ( ) {
}
public final static void pressImage ( String pressImg, String targetImg,
int x, int y) {
try {
File _file = new File ( targetImg) ;
Image src = ImageIO. read ( _file) ;
int wideth = src. getWidth ( null ) ;
int height = src. getHeight ( null ) ;
BufferedImage image = new BufferedImage ( wideth, height,
BufferedImage. TYPE_INT_RGB ) ;
Graphics g = image. createGraphics ( ) ;
g. drawImage ( src, 0 , 0 , wideth, height, null ) ;
File _filebiao = new File ( pressImg) ;
Image src_biao = ImageIO. read ( _filebiao) ;
int wideth_biao = src_biao. getWidth ( null ) ;
int height_biao = src_biao. getHeight ( null ) ;
g. drawImage ( src_biao, x,
y, wideth_biao, height_biao, null ) ;
g. dispose ( ) ;
FileOutputStream out = new FileOutputStream ( targetImg) ;
JPEGImageEncoder encoder = JPEGCodec. createJPEGEncoder ( out) ;
encoder. encode ( image) ;
out. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static void pressText ( String pressText, String targetImg,
String fontName, int fontStyle, Color color, int fontSize, int x,
int y) {
try {
File _file = new File ( targetImg) ;
Image src = ImageIO. read ( _file) ;
int wideth = src. getWidth ( null ) ;
int height = src. getHeight ( null ) ;
BufferedImage image = new BufferedImage ( wideth, height,
BufferedImage. TYPE_INT_RGB ) ;
Graphics g = image. createGraphics ( ) ;
g. drawImage ( src, 0 , 0 , wideth, height, null ) ;
g. setColor ( color) ;
g. setFont ( new Font ( fontName, fontStyle, fontSize) ) ;
g. drawString ( pressText, x, y) ;
g. dispose ( ) ;
FileOutputStream out = new FileOutputStream ( targetImg) ;
JPEGImageEncoder encoder = JPEGCodec. createJPEGEncoder ( out) ;
encoder. encode ( image) ;
out. close ( ) ;
} catch ( Exception e) {
System. out. println ( e) ;
}
}
public static String PngPath ( String path) {
BufferedImage bufferedImage;
try {
if ( ! path. substring ( path. indexOf ( "." ) ) . equals ( ".png" ) ) {
bufferedImage = ImageIO. read ( new File ( path) ) ;
String imgName = path. substring ( 0 , path. indexOf ( "." ) ) ;
BufferedImage newBufferedImage = new BufferedImage ( bufferedImage. getWidth ( ) ,
bufferedImage. getHeight ( ) , BufferedImage. TYPE_INT_RGB ) ;
newBufferedImage. createGraphics ( ) . drawImage ( bufferedImage, 0 , 0 , Color. WHITE , null ) ;
ImageIO. write ( newBufferedImage, "png" , new File ( imgName + ".png" ) ) ;
return imgName + ".png" ;
} else {
return path;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
return null ;
}
}
}
参考原文代码
https: / / my. oschina. net/ jgy/ blog/ 55702 ? fromerr= AuPHExZk