问题描述
我想显示图像,但不知道该怎么做。我是否必须安装一些库文件或者只是它可以完成我不知道。实际上我想做图像处理,但首先我必须输入图像并显示图像,然后我可以将图像处理的效果作为输出,并决定它(算法)是否正确。我只安装了日食。我也在谷歌搜索过,但无论他们建议什么都运作不好。要么我必须安装或不安装。
我尝试过以下代码:
I want to display an image but don't know what to do. Whether I have to install some library files or simply it can be done I don't know. Actually I want to do image processing, but first I have to take the image input and display image then I can get the effect of image processing as the output and decide whether it(algorithm) is correct or not. I have installed the eclipse only. I have searched in Google also but whatever they suggest is not working well. Either I have to install something or not.I have tried the following code:
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ImageTest {
public static void main(String[] args){
EventQueue.invokeLater(new Runnable()
{
public void run(){
ImageFrame frame = new ImageFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
);
}
}
class ImageFrame extends JFrame{
public ImageFrame(){
setTitle("ImageTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
ImageComponent component = new ImageComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class ImageComponent extends JComponent{
/**
*
*/
private static final long serialVersionUID = 1L;
private Image image;
public ImageComponent(){
try{
File image2 = new File("bishnu.jpg");
image = ImageIO.read(image2);
}
catch (IOException e){
e.printStackTrace();
}
}
public void paintComponent (Graphics g){
if(image == null) return;
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
g.drawImage(image, 50, 50, this);
for (int i = 0; i*imageWidth <= getWidth(); i++)
for(int j = 0; j*imageHeight <= getHeight();j++)
if(i+j>0) g.copyArea(0, 0, imageWidth, imageHeight, i*imageWidth, j*imageHeight);
}
}
它只显示一个图形窗口但是无法显示图像bishnu.jpg
It simply shows a graphical window but can't show the image "bishnu.jpg"
我应该在eclipse中安装任何东西吗?但我认为没有什么需要安装。
Should I install anything in eclipse? But I think nothing needs to install.
推荐答案
运行代码后,我会在调整路径后为我显示图像。你可以验证你的图像路径是否正确,例如尝试绝对路径?
Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?
这篇关于用Java显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!