Как я могу использовать алгоритм LZW для сжатия изображения, и после сжатия, как я могу открыть его и увидеть результат? - PullRequest
0 голосов
/ 12 июля 2020

Я пытаюсь сжать изображение, используя алгоритм LZW, используя java.

1. Первая проблема в том, что размер файла увеличился, я ожидал, что он уменьшится вместо этого

2. Вторая проблема заключается в том, что после сжатия файла, как я могу открыть файл, полученный в результате алгоритма, у меня есть следующий код:

public static HashMap<String, Integer> dictionary = new HashMap<>();

public static int dictSize = 256;

public static String P = "",filename="",BP="";
public static byte inputByte;

public static byte[] buffer = new byte[3];

public static boolean isLeft = true;

public static void compress() throws IOException {

    int i,byteToInt;
    char C;
    
    // Character dictionary 
    for(i=0;i<256;i++) {
        dictionary.put(Character.toString((char)i),i);
    }
    
    // Read input file and output file
    RandomAccessFile inputFile = new RandomAccessFile(filename,"r");
    String[] getFileNameWOExtn = filename.split("\\.");
    RandomAccessFile outputFile = new RandomAccessFile(getFileNameWOExtn[0].concat(".lzw"),"rw");
    
    try {
    
        // Read first byte to initialize P
        inputByte = inputFile.readByte();
        byteToInt = new Byte(inputByte).intValue();
        
        if(byteToInt < 0) byteToInt += 256;
        C = (char) byteToInt;
        P = ""+C;
        
        while(true) {
            inputByte = inputFile.readByte();
            byteToInt = new Byte(inputByte).intValue();
        
            if(byteToInt < 0) byteToInt += 256;
            C = (char) byteToInt;
            
            // if P+C is present in dictionary
            if(dictionary.containsKey(P+C)) {
                P = P+C;
            }
            
            else {
                BP = convertTo12Bit(dictionary.get(P));
                if(isLeft) {
                    buffer[0] = (byte) Integer.parseInt(BP.substring(0,8),2);  
                    buffer[1] = (byte) Integer.parseInt(BP.substring(8,12)+"0000",2);                   
                }
                else {
                    buffer[1] += (byte) Integer.parseInt(BP.substring(0,4),2); 
                    buffer[2] = (byte) Integer.parseInt(BP.substring(4,12),2);
                    for(i=0;i<buffer.length;i++) {
                        outputFile.writeByte(buffer[i]);
                        buffer[i]=0;
                    }
                }
                isLeft = !isLeft;
                if(dictSize < 4096) dictionary.put(P+C,dictSize++);
                
                P=""+C;
            }            
        }
    
    }
    catch(IOException ie) {
        BP = convertTo12Bit(dictionary.get(P));
        if(isLeft) {
            buffer[0] = (byte) Integer.parseInt(BP.substring(0,8),2);  
            buffer[1] = (byte) Integer.parseInt(BP.substring(8,12)+"0000",2);
            outputFile.writeByte(buffer[0]);  
            outputFile.writeByte(buffer[1]);                
        }
        else {
            buffer[1] += (byte) Integer.parseInt(BP.substring(0,4),2); 
            buffer[2] = (byte) Integer.parseInt(BP.substring(4,12),2);
            for(i=0;i<buffer.length;i++) {
                 outputFile.writeByte(buffer[i]);
                 buffer[i]=0;
            }
        }
        inputFile.close();
        outputFile.close();        
    }}public static String convertTo12Bit(int i) {
    String to12Bit = Integer.toBinaryString(i);
    while (to12Bit.length() < 12) to12Bit = "0" + to12Bit;
    return to12Bit;}

и в основном методе:

public static void main(String[] args) {
    System.out.println("image site:");
    Scanner sc = new Scanner(System.in);
    filename = sc.next();
    try {
        File file = new File(filename);
        compress();
        String[] getFileNameWOExtn = filename.split("\\.");
        System.out.println("Compression complete!Check file "+getFileNameWOExtn[0].concat(".lzw")+"!");      
    }
    catch(IOException ie) {
        System.out.println("File "+filename+" not found!");
    }
}

Входной файл - 1.jpg, а выходной - 1.lzw, например:

введите описание изображения здесь

1 Ответ

0 голосов
/ 13 июля 2020

Преобразование изображения в GIF. Затем просмотрите изображение. Вы только что использовали LZW, чтобы сжать изображение и открыть его, чтобы увидеть результат. Формат GIF использует LZW (и цветовую палитру) для сжатия.

...