[英]From BufferedImage to File: Return Type issues
Sorry if this bugs anyone, but I'm unsure of the other questions I perused searching for an answer. 抱歉,这会困扰任何人,但我不确定我一直在寻找答案的其他问题。 My issue is I'm creating a class that simply adds Gaussian Noise to the File type passed in. Once I've added the noise, I'd like to return the result to a MainScreen class I have created.
我的问题是我正在创建一个仅将高斯噪声添加到传入的文件类型的类。添加噪声后,我想将结果返回到我创建的MainScreen类。 The problem is, MainClass uses File in its JPanel.
问题是,MainClass在其JPanel中使用File。
My question is how do I convert the BufferedImage type into a File type return for my Mainscreen class without causing errors for use with Swing's Jpanel? 我的问题是如何将BufferedImage类型转换为Mainscreen类的File类型返回,而不会导致与Swing的Jpanel一起使用时出错?
Here's the code, if you'd like to see it for clarity. 这是代码,如果您想看清楚的话。 (I'm okay with this being closed if it's the wrong way to ask; I'm new to all of this and I'll be zen about this)
(如果这是错误的询问方式,我可以将其关闭,我是新手,我对此很陌生,对此我会保持禅意)
import java.io.*;
import java.util.*;
import java.lang.Math;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class NoiseGenerator {
Image image;
BufferedImage buffered;
Random r;
int width;
int height;
int index;
//The part of the code I'm referring to in the question
//addNoiseToImage takes in a File.
public BufferedImage addNoiseToImage(File imageToBeChanged, int standardDeviation){
try {
image = ImageIO.read(imageToBeChanged);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffered = (BufferedImage) image;
width = image.getWidth(null);
height = image.getHeight(null);
index = 0;
double noiseHolder;
int noiseValues[] = new int[100];
int delay = 0;
int check = 0;
do {
noiseHolder = r.nextGaussian() * standardDeviation;
check = (int) Math.round(noiseHolder);
if (check > 0) {
noiseValues[delay] = (int) noiseHolder;
delay++;
}
} while (delay <= 100);
int j;
int i;
for (j=0; j<height; j++) {
for(i=0;i<width;i++) {
index = (int) (Math.random() * (99 - 0)) + 0;
buffered.setRGB(j,i,noiseValues[index]);
}
}
return buffered; //I just have it returning a BufferedImage type to stop the error message; I'd prefer it to be a File type.
}
}
The Image I/O class provides a simple way to save images in a variety of image formats in the following example: 在以下示例中,Image I / O类提供了一种以多种图像格式保存图像的简单方法:
static boolean ImageIO.write(RenderedImage im,
String formatName,
File output) throws IOException
Note: The BufferedImage class implements the RenderedImage interface. 注意:BufferedImage类实现RenderedImage接口。 .
。
The formatName parameter selects the image format in which to save the BufferedImage. formatName参数选择用于保存BufferedImage的图像格式。
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
for more information please look at this example. 有关更多信息,请看看这个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.