gif图片转换为jpg格式 java
程序员文章站
2022-03-20 22:23:12
可参照 https://blog.csdn.net/huoji555/article/details/79595137 ......
可参照 https://blog.csdn.net/huoji555/article/details/79595137
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; }