public int nextInt(int n) {
創(chuàng)新互聯公司主營柳城網站建設的網絡公司,主營網站建設方案,app軟件定制開發(fā),柳城h5微信小程序定制開發(fā)搭建,柳城網站營銷推廣歡迎柳城等地區(qū)企業(yè)咨詢
if (n = 0)
throw new IllegalArgumentException("n must be positive");
if ((n -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) 0);
return val;
}
ImageIO.write(BufferedImage, "JPG", File);
================================
傳入Component保存圖像的方法,你試試看還有沒有變色。
public void cutScreen(Component com) {
Rectangle rect = com.getBounds();
BufferedImage bi = (BufferedImage) com.createImage(rect.width,
rect.height);
Graphics g = bi.getGraphics();
com.paint(g);
g.dispose();
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory()
|| f.getName().toLowerCase().endsWith(".jpg");
}
public String getDescription() {
return "*.jpg";
}
});
int type = jfc.showSaveDialog(null);
if (type == 0) {
File file = jfc.getSelectedFile();
name = file.getName().toLowerCase();
if (!name.endsWith("jpg")) {
String path = file.getAbsolutePath();
file = new File(path + ".jpg");
for (int i = 0; file.exists(); i++) {
file = new File(path + "(" + i + ").jpg");
}
}
try {
if (!file.exists()) {
file.createNewFile();
}
ImageIO.write(bi, "JPG", file);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
首先導入各種需要的包:
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;
讀取圖片的方法如下:
Image[] array = new Image[10];
Image image = ImageIO.read(new File("d:\\source.gif"));//根據你實際情況改文件路徑吧
array[0] = image;
圖片讀出來了。
如果你有一個Image對象,想把它寫入文件可以這樣做:
BufferedImage image = ImageIO.read(new File("d:\\source.gif"));
//要想保存這個對象的話你要把image聲明為BufferedImage 類型
ImageIO.write(image, "png", new File("f:\\test.png"));