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"))
思路:使用 java.awt.Image包下的Image可以接收图片。读取则使用ImageIO对象。代码如下:
/**
* 读取图片,首先导入以下的包
*/
import java.awt.Image
import javax.imageio.ImageIO
import java.io.*
/**
* 用Image对象来接收图片
* 路径根据实际情况修改
*/
Image image = ImageIO.read(new File("c:\\1.png"))
System.out.println(image.getSource())
下面给你提供一个实现,该实现采用了代理模式。这个实现包含两个文件,分别是Client.java和ImageIcoProxy.java,ImageIcoProxy.java负责了图片的延迟加载,你可以修改为不延迟即可。Client.java的代码为:
import java.awt.Graphics
import java.awt.Insets
import javax.swing.Icon
import javax.swing.JFrame
public class Client extends JFrame {
private static int IMG_WIDTH = 510
private static int IMG_HEIGHT = 317
private Icon imgProxy = null
public static void main(String[] args) {
Client app = new Client()
app.setVisible(true)
}
public Client() {
super("Virture Proxy Client")
imgProxy = new ImageIcoProxy("D:/test.jpg", IMG_WIDTH, IMG_HEIGHT)
this.setBounds(100, 100, IMG_WIDTH + 10, IMG_HEIGHT + 30)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public void paint(Graphics g) {
super.paint(g)
Insets insets = getInsets()
imgProxy.paintIcon(this, g, insets.left, insets.top)
}
}
ImageIcoProxy.java的代码为:
import java.awt.Component
import java.awt.Graphics
import javax.swing.Icon
import javax.swing.ImageIcon
import javax.swing.SwingUtilities
public class ImageIcoProxy implements Icon {
private ImageIcon realIcon = null
private String imgName
private int width
private int height
boolean isIconCreated = false
public ImageIcoProxy(String imgName, int width, int height) {
this.imgName = imgName
this.width = width
this.height = height
}
public int getIconHeight() {
return realIcon.getIconHeight()
}
public int getIconWidth() {
return realIcon.getIconWidth()
}
public void paintIcon(final Component c, Graphics g, int x, int y) {
if (isIconCreated) {
//已经加载了图片,直接显示
realIcon.paintIcon(c, g, x, y)
g.drawString("Just Test", x + 20, y + 370)
} else {
g.drawRect(x, y, width-1, height-1)
g.drawString("Loading photo...", x+20, y+20)
synchronized(this) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Thread.currentThread().sleep(2000)
realIcon = new ImageIcon(imgName)
isIconCreated = true
} catch (Exception e) {
e.printStackTrace()
}
c.repaint()
}
}
)
}
}
}
}