2010年4月2日星期五

在 Java 正確複製 BufferedImage 的圖像資料 (Correct way to copy BufferedImage data from Java)

import java.awt.image.BufferedImage

public static BufferedImage copy(BufferedImage source){
    return (BufferedImage)source.clone();
}

BufferedImage img1 = source;
BufferedImage img2 = copy(source);

以上兩種是有分別的
img1 會得到與 source 相同的 hash code, 所以兩者是完全相同的, 當 img1 被修改 source 同樣會被修改
img2 則是將 source 的每一個 pixel 指派到相對位置, 但兩者的 hash code 並不一樣
所以 img1 == source 會輸出 true, 而 img2 == source 會輸出 false
The different between 2 statements
img1 has the same hash code from source, that means they are equal, when img1 is modified, source will modify also
img2 is copy each pixels from source, the hash code will not the same
so img1 == source represents true, and img2 == source represents false

沒有留言 :

發佈留言