我現在有一個專案,我們基本上有一個使用 Huffman 演算法存盤顏色代碼的樹。然后,encode 方法基本上是遍歷您給它的字串并將其決議為 int 并檢查它是否等于 ColorCodes 的任何顏色值并將其附加到新字串。EncodeGraphic 方法然后遍歷圖形的線條并接收一個字串,然后使用帶有位移位運算子的編碼來“編碼”它。然后解碼,使用編碼的二進制字串作為需要遍歷多少次的鍵遍歷 BinaryTree。然后下面是 decodeGraphic,它在移動后似乎沒有回傳正確的 ARGB 值。任何幫助,將不勝感激!
public void decodeGraphic(String inputFile, String outputFile) throws InvalidHuffmanCodeException, IOException {
// Fill in this method
// Create and output file using BufferedReader (i.e., BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) )
// Note the height and width must be read in from the input file (first two lines)
// The remaining lines in the input file are the pixels
// Call the decode method for each line.
// The returned String must be parsed on the comma to get the A, R, G and B values
// Combine channels into one "bit" by using the left bit-shiffter, <<, and bitwise or, |
// Call setRGB to set the pixel
// When all the pixels are set, use ImageIO's static write method to write the graphic file (.png file)
//*************************************
int height, width;
String a, r, g, b;
int al, re, gr, bl, x = 0, y = 0;
Scanner in = new Scanner(new File(inputFile));
height = Integer.parseInt(in.nextLine());
width = Integer.parseInt(in.nextLine());
BufferedImage output = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
String[] sA;
while(in.hasNextLine()){
String temp = decode(in.nextLine());
sA = temp.split(",");
a = sA[0];
r = sA[1];
g = sA[2];
b = sA[3];
al = Integer.parseUnsignedInt(a);
re = Integer.parseUnsignedInt(r);
gr = Integer.parseUnsignedInt(g);
bl = Integer.parseUnsignedInt(b);
int updatedPixel = (al << 24) | (re << 16) | (gr << 8) | (bl);
output.setRGB(x % output.getWidth(), y % output.getHeight(), updatedPixel);
x ;
if(x % output.getHeight() == 0 && x != 0) {
y ;
}
}
ImageIO.write(output, "png", new File(outputFile));
//************************************
}
上面的代碼是我試過的,下面是回傳的(2/5 decodeGraphic 測驗通過,這是一個失敗的例子)
預期的:
255,37,21,19 255,45,30,27 255,43,28,26 255,45,28,24 255,43,26,21 255,43,24,17 255,49,30,22 255 ,48,27,24
實際的:
255,100,100,100 255,113,115,117 255,144,145,147 255,89,91,93 255,91,93,95 255,98,98,98 255,92,92,92 255,100,100,100
uj5u.com熱心網友回復:
你的位移看起來不正確。請注意,intJava 中的所有值都是有符號的。
為什么要重新實作 JDK 已經完成并測驗過的東西?
final Color color = new Color(re, gr, bl, al);
output.setRGB(x % output.getWidth(), y % output.getHeight(), color.getRGB());
或者,如果您確實需要手動實作正確的位移,請查看Color幫助的建構式:
updatedPixel = ((al & 0xFF) << 24) |
((re & 0xFF) << 16) |
((gr & 0xFF) << 8) |
((bl & 0xFF) << 0);
進一步注意,模運算可以避免和簡化,這消除了潛在錯誤的另一個來源:
output.setRGB(x, y, updatedPixel);
x;
if (x >= output.getWidth()) {
y;
x = 0;
}
注意。使用好的變數名可以讓你走得很遠。所以要么a, r, g, b要么alpha, red, green, blue。為什么要使用 2 個字符?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/525400.html
標籤:爪哇解码编码位移颜色代码
上一篇:javaIndex5outofboundsforlength5errorwhilewhileloop
下一篇:如何將介面與泛型一起使用?
