Pablo Costa

Pablo Costa

  • NA
  • 7
  • 895

Create a method to decode a RLE byte-oriented image

Aug 4 2019 6:40 PM
Hello Everyone.
 
I am trying to create a code to decode an PostScript RLE image and save it.
 
However, my output is always invalid (the raw image). I try to open it on photoshop but its always an invalid image or something like that.
 
I've wrote at least three versions of it, all of them with the same result. So i'm asking for any help here.
 
My code goes on the comments, and this is how it should be decompressed (i think my code follows what the book says).
 
The method i created:
  1. public static List < byte > RLETest(byte[] input) {  
  2.  List < byte > final = new List < byte > ();  
  3.  for (int i = 0; i < input.Length; i++) {  
  4.   var lengthByte = input[i];  
  5.   if (input[i] <= 127) {  
  6.    int currLen = input[i] + 1;  
  7.    for (int j = 0; j < currLen; j++) {  
  8.     final.Add(input[i]);  
  9.    }  
  10.   } else {  
  11.    int currLen = 257 - input[i];  
  12.    for (int j = 0; j < currLen; j++) {  
  13.     final.Add(input[i]);  
  14.    }  
  15.   }  
  16.  }  
  17.  return final;  
  18. }  
Sample file: https://drive.google.com/open?id=1-E4flwNsY6UE2ve-Ycg6Z4cwLeoKIQRu
 
Width: 212
Height: 154
Channels: 1
 
(For opening in Photoshop)
 
What PostScript Red Book says about its RLE Encoding:
 
"The RunLengthEncode filter encodes data in a simple byte-oriented format based on run length. The compressed data format is a sequence of runs, where each run consists of a length byte followed by 1 to 128 bytes of data. If the length byte is in the range 0 to 127, the following length + 1 bytes (1 to 128 bytes) are to be copied literally upon decompression. If the length is in the range 129 to 255, the following single byte is to be replicated 257 - length times (2 to 128 times) upon decompression."
 
Any help is appreciated. Thanks