2012-12-24 44 views
1

我堅持,而試圖在節目中提到的C函數convertCNGFileToJPGFile轉換cng2jpg.c轉換C函數對Perl

我一直在試圖寫在Perl一樣,但沒有與十六進制,包足夠的訣竅並解壓縮函數。

真的很感激,如果有人能在Perl如下所述寫類似的代碼。

while ((bytesRead = fread(buffer, 1, kBufferSize, inputFile))) { 
    if (!isValidCNG) { 
     if (bytesRead < 11 || strncmp("\xa5\xa9\xa6\xa9", (char *)(buffer + 6), 4)) { 
      fprintf(stderr, "%s does not appear to be a valid CNG file\n", inputFileName); 
      return 0; 
     } 
     isValidCNG = 1; 
    } 
    for (size_t i = 0; i < bytesRead; i++) 
     buffer[i] ^= 0xEF; 
    size_t bytesWritten = fwrite(buffer, 1, bytesRead, outputFile); 
    if (bytesWritten < bytesRead) { 
     fprintf(stderr, "Error writing %s\n", outputFileName); 
     return 0; 
    } 
} 

在此先感謝。

+3

做些什麼碼你有在Perl? – squiguy

+0

如果您只是將其重寫爲在Perl程序中使用它,請考慮[Inline :: C](https://metacpan.org/module/Inline::C)。 – Schwern

+0

或者您可以使用Perl中的許多圖像處理庫之一,例如[Imager](https://metacpan.org/module/Imager)。 – Schwern

回答

5

如果我讀正確的代碼,所有它做(除了有效性檢查)與字節0xEF文件中的異或每一字節(即翻轉所有,但每個字節的第五個最低位)。在Perl中,你可以實現與:

local $/ = \(2**16); # ignore line breaks, read in 64 kiB chunks 
while (<>) { 
    $_ ^= "\xEF" x length; 
    print; 
} 

有效性檢查只是檢查輸出實際上是一個有效的JPEG文件—具體而言,7日到輸出文件的10個字節包含口令字"JFIF"(當與0xEF異或時變爲"\xa5\xa9\xa6\xa9")。一般情況下,除非您希望頻繁地將這些代碼運行在實際不是CNG文件的文件上,否則我不會爲此而煩惱,因爲之後檢查輸出的有效性會更容易。如果您(此外,檢查將,如果解碼後的文件實際上是一個Exif JPEG圖像,它有神奇的字"Exif",而不是失敗)

要包括的檢查,這樣的事情應該這樣做:

local $/ = \(2**16); # ignore line breaks, read in 64 kiB chunks 
while (<>) { 
    $_ ^= "\xEF" x length; 
    die "Not a valid CNG file" if $. == 1 and not /^.{6}(JFIF|Exif)/s;   
    print; 
} 

詩篇。如果此代碼運行速度太慢,我建議兩種可能的改進:1)使用一個更大的緩衝區,和b)預分配0xEF的面具字節每次重建它的飛行,而不是:

local $/ = \(2**20); # ignore line breaks, read in 1 MiB chunks 
my $mask = "\xEF" x $$/; 
while (<>) { 
    $_ ^= substr($mask, 0, length); 
    die "Not a valid CNG file" if $. == 1 and not /^.{6}(JFIF|Exif)/s;   
    print; 
} 
+0

非常感謝它是工作。 –