我正在從點鈔機讀取一個串行埠,我希望得到從點鈔機發送的鈔票的序列號。
我從機器讀取位元組陣列并使用下面的代碼將其轉換為二進制字串:
public void serialEvent(SerialPortEvent serialPortEvent) {
ArrayList<String> list = new ArrayList<>();
String s1 = new String();
if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
return;
}
byte[] readBuffer = new byte[comPort.bytesAvailable()];
int numRead = comPort.readBytes(readBuffer, readBuffer.length);
//System.out.println("Read " numRead " bytes.");
for (Byte b : readBuffer) {
//image is more than 500 bytes, all other data is less than 500
if (numRead <= 500) {
break;
}
s1 = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
//new line byte, everytime it shows up I add a new line
if (s1.equals("01000101")) {
System.out.println();
continue;
}
System.out.print(s1);
下圖是我從 System.out 得到的 s1 String 的截圖,你可以看到有 1 代表的序列號,背景是 0 代表的。

我現在的問題是如何將此字串轉換為影像檔案?我猜我需要從這個字串制作一個 1d 或 2d 陣列并制作一個影像,其中 0 代表白色像素,1 代表黑色像素,但我不知道該怎么做,我需要一些幫助嗎?
提前致謝。
編輯:
我可以使用以下代碼獲取 ASCII 輸出:
public void serialEvent(SerialPortEvent serialPortEvent) {
InputStream in = comPort.getInputStream();
Reader in2 = new InputStreamReader(in, StandardCharsets.US_ASCII);
try
{
for (int j = 0; j < 10000; j) {
System.out.print((char)in2.read());
in.close();
}
} catch (Exception e) { e.printStackTrace(); }
comPort.closePort();
}
});

uj5u.com熱心網友回復:
PBM 檔案格式
您幾乎可以直接將 ASCII 藝術字串寫入 PBM 檔案。在此處檢查檔案格式:https ://netpbm.sourceforge.net/doc/pbm.html
其他檔案格式
如果您更喜歡創建 BMP | 動圖 | JPEG | 巴布亞新幾內亞| 國際電影節 | WBMP(ImageIO支持的格式),請遵循以下步驟:
- 首先使用它的建構式創建一個 BufferedImage 。
- 從 BufferedImage 中檢索圖形背景關系。
- 將像素繪制到 Graphics 背景關系中。
- 使用setColor(Color.white)和fillRect初始化背景。
- 為每個 1 繪制一個黑色矩形:setColor , fillRect 你只需要計算你的位數,這樣你就知道矩形的坐標。
- 最后使用ImageIO.write()將 BufferedImage 保存到檔案
從您的 ascii 字串轉換可能如下所示:
Graphics g = ...
// assuming your string values are stored in the array strings
for(int y=0; y<strings.length, y ) {
String line = strings[y];
for(int x=0; x<line.length(); x ) {
if (line.charAt(x)=='1') {
g.setColor(Color.black);
g.fillRect(x, y, 1, 1);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/523550.html
標籤:爪哇图片串行端口像素
