ImgFormatUtils(图片拉伸)
Posted blakflash000
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ImgFormatUtils(图片拉伸)相关的知识,希望对你有一定的参考价值。
import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; public class ImgFormatUtils { public static void formatImage(String file) { //读取图片 BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } //字节流转图片对象 Image bi = null; try { bi = ImageIO.read(in); } catch (IOException e) { e.printStackTrace(); } //构建图片流 BufferedImage tag = new BufferedImage(400, 700, BufferedImage.TYPE_INT_RGB); //绘制改变尺寸后的图 tag.getGraphics().drawImage(bi, 0, 0,400, 700, null); //输出流 BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); try { encoder.encode(tag); } catch (IOException e) { e.printStackTrace(); } // try { // ImageIO.write(tag, "JPG",out); // } catch (IOException e) { // e.printStackTrace(); // } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } public static byte[] formatImage2Bytes(String file) { //读取图片 BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } //字节流转图片对象 Image bi = null; try { bi = ImageIO.read(in); } catch (IOException e) { e.printStackTrace(); } //构建图片流 BufferedImage tag = new BufferedImage(400, 700, BufferedImage.TYPE_INT_RGB); //绘制改变尺寸后的图 tag.getGraphics().drawImage(bi, 0, 0,400, 700, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(tag, "JPG",out); InputStream is = new ByteArrayInputStream(out.toByteArray()); byte[] buff = new byte[200]; int rc = 0; while (-1 != (rc = is.read(buff , 0 , 200)) ){ out.write(buff, 0, rc); } } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); out.close(); } catch(IOException e){} } return out.toByteArray(); } }
以上是关于ImgFormatUtils(图片拉伸)的主要内容,如果未能解决你的问题,请参考以下文章