2014-11-21 4 views
1

내가하려고하는 것은 이미지를 찍어서 바둑판 모양으로 만드는 것입니다. 시작 이미지는 다음과 같아야합니다. http://i1146.photobucket.com/albums/o525/walroid/letter_Q_grayscale_zpsd3b567a7.jpg 그런 다음 이미지가 타일로 바뀌면 다음과 같이 표시됩니다. http://i1146.photobucket.com/albums/o525/walroid/replicate_example_zps5e5248e8.jpg 내 코드에서 그림은 메서드로 호출 된 배열에 저장됩니다. 내가하고 싶은 것은 배열을 복사 한 다음 이미지를 복제 할 다른 배열에 넣는 것입니다. 어떻게해야합니까? 당신은 배열의 "deep copy"할 필요가배열을 복사하려면 어떻게합니까?

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); 
     } 
    } 
} 
+0

경우 이전 질문 중 어떤 대답을 받아 들였습니다. StackOverflow에서 도움을 받거나 정답을 제공 한 경우 답변을 허용하거나 취소 표시하는 것이 적절합니다. 이것은 미래 방문자가 당신의 문제를 해결 한 것과 그들이 비슷한 이슈를 가지고 있다면 도움이되었을 수도있는 것을 알게합니다. – SnakeDoc

답변

3

: 여기 내 전체 코드입니다. 간단히 배열을 새로운 변수에 복사하면 참조 (shallow copy) 만 할당되며 배열 중 하나에서 데이터를 조작하면 둘 다 변경됩니다.

얕은 복사 :

String[] myArray2 = myArray1; 

이 같은 데이터를 가리키는 두 참조를 본질적으로이있을 것이다. 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 개체를 사용하도록 수정할 수 있습니다.

+0

코드에 구현하려고 시도했지만 컴파일되지만 출력 이미지가 원본과 동일합니다. 여기 내가 그것을 불렀던 방법이있다 \t else if (function.("- tile")) {배열을 선언하고이를 메서드로 호출하고 있습니다. \t String inputFileName = args [1]; \t String outputFileName = args [2]; \t \t int [] [] imageArr = readGrayscaleImage (inputFileName); \t int [] [] tileArr = tile (imageArr); \t \t writeGrayscaleImage (outputFileName, tileArr); } –

+0

당신이 제공 한 코드 스 니펫은 실제로 어떻게/무엇을하고 있는지 알려주지 않습니다.하지만 객체 (배열)를 복제하는 것과 정확히 같아야합니다. 이것이 당신에게주는 것은 동일한 요소를 포함하지만 서로를 참조하거나 동일한 데이터를 참조하지 않는 두 개의 개별 배열을 가졌다는 것입니다. – SnakeDoc

+0

내 코드와 행에 메서드를 구현하려고 시도했습니다. \t \t myArray2 [i] = myArray1 [i]; 그것은 나에게 "비교할 수없는 유형"이라는 오류를줍니다. 또한 myArray1을 double 배열로 선언했습니다. –

1

Array 클래스를 사용하고 정적 메소드 Array.copyOf를 호출 (배열, 사항 Array.length는) 매우 편리 그래서 myArray1 이전 배열이며 myArray2 난 당신이하지 않은 눈치 새로운 배열 다음 myArray2 = Array.copyOf(myArray1, myArray1.length)