Java如何读取文件夹中所有图片,并显示出来

Java如何读取文件夹中所有图片,并显示出来,第1张

说一下思路吧,首先遍历文件夹,找到对应后缀的文件(png,jpg之类的),然后创建Bitmap对象,使用inputStream将文件转成bitmap对象,之后使用imageview或者GLview显示图片即可。

注意对大图进行压缩,结束时图片必须回收处理,bitmap.recycle()否则图片多了内存溢出

下面给你提供一个实现,该实现采用了代理模式。这个实现包含两个文件,分别是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()

}

}

)

}

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/8045400.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-12
下一篇 2023-04-12

发表评论

登录后才能评论

评论列表(0条)

保存