JAVA实现bmp转换JPEG_Java gif图片转换为jpg格式
下面通過(guò)代碼給大家介紹Java gif圖片轉(zhuǎn)換為jpg格式,具體代碼如下所示:
if(fileName.toLowerCase().endsWith(".gif")){//由于頭像上傳支持JPG、JPEG、BMP、GIF、PNG格式圖片.而商湯人臉設(shè)備僅支持JPG、JPEG、BMP、PNG,故如圖片為GIF格式需要轉(zhuǎn)換
fileParams.put("avatarFile", api.GifToJpg(avatar_file));
}else{
fileParams.put("avatarFile", api.getBytes(avatar_file));
}
/**
* 將文件轉(zhuǎn)換為byte二進(jìn)制流
* @param f
* @return
*/
public static byte[] getBytes(File f) {
try {
InputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1)
out.write(b, 0, n);
in.close();
out.close();
return out.toByteArray();
} catch (IOException e) {
logger.error("***請(qǐng)?jiān)O(shè)置文件路徑***");
e.printStackTrace();
}
return null;
}
/**
* 將gif格式圖片轉(zhuǎn)換為jpg格式文件,并直接返回byte二進(jìn)制流
* @param file
* @return
*/
public static byte[] GifToJpg(File file){
BufferedImage bufferedImage;
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
try {
// read image file
bufferedImage = ImageIO.read(file);
// create a blank, RGB, same width and height, and a white
BufferedImage newBufferedImage = new BufferedImage(
bufferedImage.getWidth(), bufferedImage.getHeight(),
BufferedImage.TYPE_INT_RGB);
// TYPE_INT_RGB:創(chuàng)建一個(gè)RBG圖像,24位深度,成功將32位圖轉(zhuǎn)化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0,Color.WHITE, null);
// write to jpeg file
ImageIO.write(newBufferedImage, "jpg",out);//轉(zhuǎn)換輸出到二進(jìn)制數(shù)組流
//ImageIO.write(newBufferedImage, "jpg",new File("c:\\java.jpg"));//轉(zhuǎn)換輸出到文件
return out.toByteArray();//二進(jìn)制流
} catch (IOException e) {
logger.error("***GifToJpg方法報(bào)錯(cuò)***");
e.printStackTrace();
}
return null;
}
知識(shí)點(diǎn)擴(kuò)展:
用java將png圖片轉(zhuǎn)換成jpg格式的圖片
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ConvertImageFile {
public static void main(String[] args) {
BufferedImage bufferedImage;
try {
//read image file
bufferedImage = ImageIO.read(new File("c:\\java.png"));
// create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
//TYPE_INT_RGB:創(chuàng)建一個(gè)RBG圖像,24位深度,成功將32位圖轉(zhuǎn)化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
// write to jpeg file
ImageIO.write(newBufferedImage, "jpg", new File("c:\\java.jpg"));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
總結(jié)
以上所述是小編給大家介紹的Java gif圖片轉(zhuǎn)換為jpg格式,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)谷谷點(diǎn)程序網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
總結(jié)
以上是生活随笔為你收集整理的JAVA实现bmp转换JPEG_Java gif图片转换为jpg格式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: matlab中clear;close;c
- 下一篇: Java使用百度地图API,根据地址,查