Java 获取图片的大小、宽、高

时间:2021-04-27 14:38:17

参考:https://www.cnblogs.com/hongten/archive/2012/11/26/hongten_java_ImageReader_BufferedImage.html

 import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import javax.imageio.ImageIO; public class Picture {
public static void main(String[] args) throws FileNotFoundException, IOException {
File picture = new File("E:/PrintScreen/StarSky.jpg");
BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture)); System.out.println(String.format("Size: %.1f KB", picture.length()/1024.0));
System.out.println("Width: " + sourceImg.getWidth());
System.out.println("Height: " + sourceImg.getHeight());
}
}

这个没看懂!

 import java.io.File;
import java.io.IOException;
import java.util.Iterator; import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream; public class Picture {
public static void main(String[] args) {
String srcPath = "E:/PrintScreen/1.jpg"; File file = new File(srcPath);
try {
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = (ImageReader) readers.next();
ImageInputStream iis = ImageIO.createImageInputStream(file);
reader.setInput(iis, true);
System.out.println("width: " + reader.getWidth(0));
System.out.println("height: " + reader.getHeight(0));
} catch (IOException e) {
e.printStackTrace();
}
}
}

##########################################################################

注意:图片是预先存放在Java Project下的Package中

Java 获取图片的大小、宽、高

 import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL; import javax.imageio.ImageIO; public class GetImageSize {
public static void main(String[] args) throws IOException {
BufferedImage bi = null; try {
URL u = GetImageSize.class.getClassLoader().getResource("images/background.png");
bi = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
Image img = bi; System.out.println(img.getWidth(null));
System.out.println(img.getHeight(null));
}
}