Как мне скопировать массив?
Я пытаюсь сделать изображение и сделать его мозаичным. Начальное изображение должно выглядеть следующим образом. http://i1146.photobucket.com/albums/o525/walroid/letter_Q_grayscale_zpsd3b567a7.jpg А потом, что изображение превращается в плитки, то оно должно выглядеть так: http://i1146.photobucket.com/albums/o525/walroid/replicate_example_zps5e5248e8.jpg В моем коде изображения сохраняются в массив, который вызывается в метод. Что я хочу сделать, это скопировать этот массив, а затем поместить его в другой массив, который будет копировать изображение. Как я могу это сделать? Вот весь мой код:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class ImageProcessor {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Not enough arguments");
System.exit(-1);
}
String function = args[0];
if (function.equals("-reflectV")) {
String inputFileName = args[1];
String outputFileName = args[2];
int[][] imageArr = readGrayscaleImage(inputFileName);
int[][] reflectedArr = reflectV(imageArr);
writeGrayscaleImage(outputFileName, reflectedArr);
} else if (function.equals("-reflectH")) {
String inputFileName = args[1];
String outputFileName = args[2];
int[][] imageArr = readGrayscaleImage(inputFileName);
int[][] reflectedArr = reflectH(imageArr);
writeGrayscaleImage(outputFileName, reflectedArr);
} else if (function.equals("-ascii")) {
String inputFileName = args[1];
String outputFileName = args[2];
int[][] imageArr = readGrayscaleImage(inputFileName);
int[][] reflectedArr = reflectV(imageArr);
try {
PrintStream output = new PrintStream(new File("output.txt"));
} catch (java.io.FileNotFoundException ex) {
System.out.println("Error: File Not Found");
System.exit(-1);
}
} else if (function.equals("-adjustBrightness")) {
String amount = args[1];
int a = Integer.parseInt(amount);
System.out.print(a)
String inputFileName = args[1];
String outputFileName = args[2];
int[][] imageArr = readGrayscaleImage(inputFileName);
int[][] brightnessArr = adjustBrightness(imageArr);
writeGrayscaleImage(outputFileName, brightnessArr);
} else
System.out.println("That is not a valid choice");
system.exit(-1)
public static int[][] reflectV ( int[][] arr){
int[][] reflected = new int[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
reflected[i][j] = arr[i][arr[i].length - 1 - j];
}
}
return reflected;
}
public static int[][] reflectH ( int[][] arr){
int[][] reflected = new int[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
reflected[j][i] = arr[i][arr[j].length - 1 - j];
}
}
return reflected;
}
public static int[][] adjustBrightness ( int[][] arr){
int[][] brightness = new int[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
RGB
}
}
return brightness;
}
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
//set all its pixel values based on values in the input array
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);
}
}
//write the image to a file
File imageFile = new File(filename);
ImageIO.write(image, "jpg", imageFile);
} catch (IOException ioe) {
System.err.println("Problems writing file named " + filename);
System.exit(-1);
}
}
}
3 ответа
Вам нужно сделать "deep copy
"массива. Простое копирование массива в новую переменную только назначит ссылку (shallow copy
), и если вы будете манипулировать данными в одном из массивов, это изменит оба.
Мелкая копия:
String[] myArray2 = myArray1;
По существу, это будет иметь 2 ссылки, указывающие на одни и те же данные. Если вы измените что-нибудь в myArray2
, это также изменится в myArray1
,
Глубокая Копия:
Есть несколько способов сделать глубокую копию. Очевидным способом является итерация по вашему массиву и копирование каждого элемента по одному в новый массив.
String[] myArray2 = new String[myArray1.length];
for (int i = 0; i < myArray1.length; i++) {
myArray2[i] = myArray1[i];
}
Иногда более простой / быстрый способ serialize
ваш массив, а затем десериализовать его, пока он еще находится в памяти. Это заставляет JVM обрабатывать десериализованный массив как совершенно новый массив (так сказать, "без присоединенных строк").
Вот пример из моего старого проекта:
/**
* Clones an object creating a brand new
* object by value of input object. Accomplishes this
* by serializing the object, then deservializing it.
*
* @param obj Input Object to clone
* @return a new List<Product> type cloned from original.
* @throws IOException If IOException
* @throws ClassNotFoundException If ClassNotFoundException
*/
private static List<Product> cloneProdList(Object obj) throws IOException, ClassNotFoundException {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream obj_out = new java.io.ObjectOutputStream(bos);
obj_out.writeObject(obj);
java.io.ByteArrayInputStream bis = new java.io.ByteArrayInputStream(bos.toByteArray());
java.io.ObjectInputStream obj_in = new java.io.ObjectInputStream(bis);
@SuppressWarnings("unchecked")
List<Product> newObj = (List<Product>)obj_in.readObject();
bos.close();
bis.close();
obj_out.close();
obj_in.close();
return newObj;
}
Этот код занимает List
введите в качестве ввода (ну, это на самом деле приводит к Object
типа), сериализует, а затем десериализует, находясь в памяти, а затем возвращает обратно в List
объект и возвращает новый объект обратно из метода.
Вы можете изменить его, чтобы использовать Array
объект вместо этого довольно легко. (Тип массива [] будет автоматически в Array
для тебя)
Использование класса Array и вызов статического метода Array.copyOf(array, array.length) очень удобен, так что если myArray1 - предыдущий массив, а myArray2 - новый массив, myArray2 = Array.copyOf(myArray1, myArray1.length)
https://docs.oracle.com/javase/7/docs/api/java/lang/System.html
Вы можете использовать System.arraycopy в цикле for для копирования из одного массива в другой.