如何从JLabel图标中获取ByteArray?

时间:2021-11-22 21:48:19

I'm trying to get ByteArray from icon of JLabel and then store it to my database.
The reason being because when I open image in my JLabel it gets resized to 300x300 pixels, so I want to save that resized picture to my database, to keep my database lightweight.
I want to do that 'on the fly' without having to save that resized picture on the disk.

我正在尝试从JLabel的图标中获取ByteArray,然后将其存储到我的数据库中。原因是当我在JLabel中打开图像时,它被调整为300x300像素,所以我想将调整大小的图片保存到我的数据库,以保持我的数据库轻量级。我希望“即时”执行此操作,而无需将已调整大小的图片保存在磁盘上。

I have no problem to convert the files from the disk to a ByteArray and storing those ByteArrays in a SQLite database.
But getting the ByteArray from an icon of a JLabel is a mission impossible for me.
I don't know is it even possible.

将文件从磁盘转换为ByteArray并将这些ByteArrays存储在SQLite数据库中没有问题。但是从一个JLabel的图标中获取ByteArray对我来说是不可能完成的任务。我不知道它是否可能。

So help me out, guys.
Is there any way to do that?

伙计们,帮帮我吧。有没有办法做到这一点?

1 个解决方案

#1


0  

The JLabel is simply a placeholder for the image, you are still using the image object. Wouldn't it be easier to simply convert the image into a byte array?

JLabel只是图像的占位符,您仍在使用图像对象。简单地将图像转换为字节数组会不会更容易?

File f = new File("img.jpg");
BufferedImage image = ImageIO.read(fnew);
ByteArrayOutputStream b =new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b );
byte[] imageInByte = b.toByteArray();

Or if you wanted to retrieve the image from a JLabel you can use:

或者,如果您想从JLabel检索图像,可以使用:

Icon icon = label.getIcon();
BufferedImage image = new BufferedImage(icon.getIconWidth(),
            icon.getIconHeight(),BufferedImage.TYPE_INT_RGB);

#1


0  

The JLabel is simply a placeholder for the image, you are still using the image object. Wouldn't it be easier to simply convert the image into a byte array?

JLabel只是图像的占位符,您仍在使用图像对象。简单地将图像转换为字节数组会不会更容易?

File f = new File("img.jpg");
BufferedImage image = ImageIO.read(fnew);
ByteArrayOutputStream b =new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b );
byte[] imageInByte = b.toByteArray();

Or if you wanted to retrieve the image from a JLabel you can use:

或者,如果您想从JLabel检索图像,可以使用:

Icon icon = label.getIcon();
BufferedImage image = new BufferedImage(icon.getIconWidth(),
            icon.getIconHeight(),BufferedImage.TYPE_INT_RGB);