這篇文章主要介紹了怎么在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格式的文章就介紹到這了,更多相關的內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。