我所拥有的是充当图像处理器的代码。代码有很多方法,但我想知道的是如何调用方法,以便当用户运行程序(来自CMD)而不是只输入java imageprocessor时,他们会输入java -imageprocessor -ascii image。 jpg image.txt。这意味着程序读取该图像并生成它的ascii版本,并将其保存在名为image.txt的文件中。要调用方法,用户可以输入类似-writeGrayscaleImage的方法来调用方法writeGrayscaleImage。那么我将如何实现它以便用户调用该方法?到目前为止,这是我的代码:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class ImageProcessor {
public static int[][] readGrayscaleImage(String filename) {
int [][] result = null; //create the array
try {
File imageFile = new File(filename); //create the file
BufferedImage image = ImageIO.read(imageFile);
int height = image.getHeight();
int width = image.getWidth();
result = new int[height][width]; //read each pixel value
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = image.getRGB(x, y);
result[y][x] = rgb & 0xff;
}
}
}
catch (IOException ioe) {
System.err.println("Problems reading file named " + filename);
System.exit(-1);
}
return result;
}
public static void writeGrayscaleImage(String filename, int[][] array) {
int width = array[0].length;
int height = array.length;
try {
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); //create the image
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = array[y][x];
rgb |= rgb << 8;
rgb |= rgb << 16;
image.setRGB(x, y, rgb);
}
}
File imageFile = new File(filename);
ImageIO.write(image, "jpg", imageFile);
}
catch (IOException ioe) {
System.err.println("Problems writing file named " + filename);
System.exit(-1);
}
}
}
答案 0 :(得分:0)
Brandon MacLeod先生, 您必须创建一个main方法并提供方法名称文件名作为命令行参数,并根据main方法调用适当的方法。或者您可以使用静态块来调用方法,因为静态块将在main方法之前运行,您也可以向静态块提供参数。
答案 1 :(得分:0)
在main方法中,检查命令行参数,然后根据值将程序路由到正确的方法。例如:
public static void main(String[] args)
{
if (args[0].equals("-writeGrayscaleImage")) // in reality you should check the whole array for this value
{
ImageProcessor.writeGrayscaleImage(..., ...);
}
}
如果你使用像Apache Commons CLI这样的库,你可以这样做:
public static void main(String[] args)
{
// ... insert CLI setup code
if (cmd.hasOption("writeGrayscaleImage") && cmd.hasOption("image"))
{
ImageProcessor.writeGrayscaleImage(cmd.getOptionValue("image"), ...);
}
}
答案 2 :(得分:0)
例如:
class Program{
public static void main (String[] args){
switch (args[0]){
case "readGrayscaleImage":
ImageProcessor.readGrayScaleImage(args[1]);
break;
case "writeGrayscaleImage":
ImageProcessor.writeGrayscaleImage(args[1], array); //You'll have to get your array somehow
break;
}
}
}
这假定第一个参数(args [0])是方法名称(确切地说),第二个参数(args 1)是文件的名称。我不确定你期望从命令行输入一个数组,所以你必须自己解决这个问题。您可以轻松添加新方法,只需遵循以下格式:
case "methodName":
ImageProcessor.methodName(arguments);
如果您决定将main方法添加到ImageProcessor类,则应使用methodName(args)
而不是ImageProcessor.methodName(args)
调用方法