1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| 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.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream;
public class ReduceImg {
public static void reduceImg(String imgsrc, String imgdist) { try { File srcfile = new File(imgsrc); if (!srcfile.exists()) { System.out.println("文件不存在"); } int[] results = getImgWidthHeight(srcfile);
int widthDist = results[0]; int heightDist = results[1]; Image src = ImageIO.read(srcfile);
BufferedImage tag = new BufferedImage(widthDist, heightDist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src.getScaledInstance(widthDist, heightDist, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } catch (Exception ef) { ef.printStackTrace(); } }
public static int[] getImgWidthHeight(File file) { InputStream is = null; BufferedImage src = null; int result[] = {0, 0}; try { is = new FileInputStream(file); src = ImageIO.read(is); result[0] = src.getWidth(null); result[1] = src.getHeight(null); is.close(); } catch (Exception ef) { ef.printStackTrace(); }
return result; }
}
|