JAVA实现bmp转换JPEG_Java gif图片转换为jpg格式
下面通過代碼給大家介紹Java gif圖片轉換為jpg格式,具體代碼如下所示:
if(fileName.toLowerCase().endsWith(".gif")){//由于頭像上傳支持JPG、JPEG、BMP、GIF、PNG格式圖片.而商湯人臉設備僅支持JPG、JPEG、BMP、PNG,故如圖片為GIF格式需要轉換
fileParams.put("avatarFile", api.GifToJpg(avatar_file));
}else{
fileParams.put("avatarFile", api.getBytes(avatar_file));
}
/**
* 將文件轉換為byte二進制流
* @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("***請設置文件路徑***");
e.printStackTrace();
}
return null;
}
/**
* 將gif格式圖片轉換為jpg格式文件,并直接返回byte二進制流
* @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:創建一個RBG圖像,24位深度,成功將32位圖轉化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0,Color.WHITE, null);
// write to jpeg file
ImageIO.write(newBufferedImage, "jpg",out);//轉換輸出到二進制數組流
//ImageIO.write(newBufferedImage, "jpg",new File("c:\\java.jpg"));//轉換輸出到文件
return out.toByteArray();//二進制流
} catch (IOException e) {
logger.error("***GifToJpg方法報錯***");
e.printStackTrace();
}
return null;
}
知識點擴展:
用java將png圖片轉換成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:創建一個RBG圖像,24位深度,成功將32位圖轉化成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();
}
}
}
總結
以上所述是小編給大家介紹的Java gif圖片轉換為jpg格式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對谷谷點程序網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
總結
以上是生活随笔為你收集整理的JAVA实现bmp转换JPEG_Java gif图片转换为jpg格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab中clear;close;c
- 下一篇: Vue使用百度分享,组件切换、销毁分享失