기본 콘텐츠로 건너뛰기

개발 공부 - [Huffman Coding] 압축 (Compression) - 6

제5단계 인코딩하기

압축파일의 맨 앞부분(header)에 파일(원본)을 구성하는 run들에 대한 정보를 기록한다.
이 때 원본 파일의 길이도 함께 기록한다. (왜 필요할까?)

: 각각의 run 들에게 어떤 codeword를 부여했는지 알아야 복원 가능하기 때문에 codeword에 대한 정보를 기록한다.
아니면 frequency에 대한 정보를 저장한다.


outputFrequencies

private void outputFrequencies(RandomAccessFile fIn,
 RandomAccessFile fOut) throws IOException {
    //fIn : 압축할 파일
    //fOut : 압축된 파일
    
     fOut.writeInt(runs.size());
    // 먼저 run의 개수를 하나의 정수로 출력한다.

     fOut.writeLong(fIn.getFilePointer());
    // 원본 파일의 크기(byte 단위)를 출력한다.    

    for (int j = 0; j < runs.size(); j++) {
    // 
         Run r = runs.get(j);
         fOut.write(r.symbol); // write a byte
         fOut.writeInt(r.runLen);
         fOut.writeInt(r.freq);
    }
}


compressFile

public void compressFile(String inFileName, RandomAccessFile fIn)
//fin은 압축할 파일, inFileName은 그 파일 이름이다. (압축 파일명 정하기 가능)
 throws IOException {
    String outFileName = new String(inFileName+”.z");
    // 압축 파일의 이름은 압축할 파일의 이름에 확장자를 . z를 붙인 것이다.
    RandomAccessFile fOut = new RandomAccessFile(outFileName,”rw");
    //압축파일을 여기서 생성하여 outputFrequncies와 encode 메소드에서 제공한다.
     collectRuns(fIn);
     outputFrequencies(fIn,fOut);
     createHuffmanTree();
     assignCodewords(theRoot, 0, 0);
     storeRunsIntoArray(theRoot);
     fIn.seek(0);
    encode(fIn, fOut); //중요!
}


public class HuffmanCoding {
     …
     public void compressFile(String inFileName, RandomAccessFile fIn)
     throws IOException {
         …
     }

    static public void main (String args[]) {
         HuffmanCoding app = new HuffmanCoding();
        RandomAccessFile fIn;
        try {
            fIn = new RandomAccessFile(“sample.txt”,”r");
             app.compressFile(“sample.txt”, fIn);
            fIn.close();
        } catch (IOException io) {
            System.err.println("Cannot open " + fileName);
        }
    }
}


encode() 
- encode를 위하여 하나의 buffer를 사용한다.
* buffer는 32비트 정수를 사용하여 구현한다.

1) 앞에서부터 데이터파일을 읽어서 하나의 run 을 인식한다.
2) run을 인식하여 값을 할당한 뒤 buffer에 채운다.
3) buffer 에 만약에 빈 자리가 run에 할당된 값 만큼 없으면 
file 에 output 한 뒤 buffer를 비우고, 다시 채운다
예시 : 1100110* 같이 1자리 남은 상태에서 111 이 할당될 경우
1100111 로 채우고 buffer를 채우고 다시 새로운 버퍼에 00000011 같이
11 남은 것을 마저 채우고 또 shift 해서 110을 넣을 경우
00011110 과 같이 만든다.


encode

private void encode(RandomAccessFile fIn, RandomAccessFile fOut) {
    while there remains bytes to read in the file {
         recognise a run;
        find the codeword for the run;
        //HashMap - map.get(newRun, symbol, runlength);
        //임시적 run 객체를 생성하여 그걸 key로 해서 hashmap에 저장한다.

         pack the codeword into the buffer;
         if the buffer becomes full
             write the buffer into the compressed file;
         }
        if buffer is not empty {
             append 0s into the buffer;
             write the buffer into the compressed file;
        }
}

파일 끝에 도달해서 while문을 빠져나왔을 시, 
buffer가 full이 안 되었다면 아직 몇 bit의 코드가 남아있을 수 있다.
그러면 잔여 공간에 0을 채워서 한 바이트로 만들어 주고 마지막으로 output 할 수 있게 한다.
    

class HuffmanEncoder
    public class HuffmanEncoder {
         static public void main (String args[]) {
             String fileName = "";
             HuffmanCoding app = new HuffmanCoding();
             RandomAccessFile fIn;
             Scanner kb = new Scanner(System.in);
             try {
                 System.out.print("Enter a file name: ");
                 fileName = kb.next();
                 fIn = new RandomAccessFile(fileName,"r");
                 app.compressFile(fileName,fIn);
                 fIn.close();
             } catch (IOException io) {
             System.err.println("Cannot open " + fileName);
             }
     }
}


메인 함수 내에 삽입하지 않고 이제 HuffmanEncoder로 class를 생성하고,
filename도 입력받을 수 있게 한다.
(내용은 똑같은데 encode 함수 추가로 인해서 encoder랑 decoder 분리하기 위함)








댓글

이 블로그의 인기 게시물

Ebook - 전자책 drm 상관 없이 pdf로 만들기

yes24와 교보문고에서 ebook을 구매 해야 했는데 너무 불편하고, 필기가 매우 화날 정도로 안 좋아서 원시적으로 사용하기로 했다. 1. 목적 : ebook에서 필기 및 사용이 불편하여 pdf로 변환  2. 용도 : 개인 사용 목적이며 화질이 다소 저하되어도 필기만 용이하면 상관 없음 3. 방법 1) 휴대폰 및 카메라로 동영상을 촬영했다. DRM 때문에 프로그램으로는 촬영이 안 되는 것을 확인했다. 2) 마우스 클릭 해주는 매크로를 사용했다. (1) key_macro.exe > https://blog.daum.net/pg365/250 듀얼 모니터에서 위치 이탈 현상이 있긴 해도 괜찮았다. (2) AutoClick.exe > http://bestsoftwarecenter.blogspot.com/2011/02/autoclick-22.html 이 걸로 잘 사용했다. 3초마다 한 번 클릭하도록 사용했다. 3) 동영상을 이미지로 변경해주는 프로그램을 사용했다. Free Video to JPG Converter > https://free-video-to-jpg-converter.kr.uptodown.com/windows 일 하면서 듀얼 모니터에 켜 놨는데 속도가 괜찮았다. * Every frame 으로 사용해야 한다. 4) 중복 사진 제거해주는 프로그램을 사용했다. VlsiPics  > http://www.visipics.info/index.php?title=Main_Page 생각보다 느리니 퇴근시에 걸어놓고 가면 된다. 한번 play가 끝나면 Auto-select 하고 Delete 하면 된다. 5) 이미지를 일괄 Crop 작업 해주는 프로그램을 사용했다. JPEGCrops > https://jpegcrops.softonic.kr/ * https://joker1209.tistory.com/11 도 참고했다. View -> Large 로 크게 본 뒤, Edit -> Syncronize Crops 로 일괄 동일하게 적용하는 방식을 사

개발 공부 - json JSONObject 사용 시 백슬래시(\), 원화 표시(\) 제거 및 치환

import org.json.simple.JSONObject; String dataString = new String(authData.toJSONString()); dataString = dataString.replaceAll("\\\\", ""); String 으로 안 바뀌는 가 싶어서 String 으로 변환 해 주고 작업 하였다. 사실 toJSONString 해도 정상 동작 해야 하는데 이유를 잘 모르겠음. 그리고 나서 다시 이클립스 구동 하니 toString 도 먹은 걸로 봐서 이상하다고 생각! String dataString = authData.toString(); dataString = dataString.replaceAll("\\\\", ""); 어쨌든 백 슬래시 제거를 해줘야 하는데 \\ 도 아니고 \\\\를 해야 변환이 가능했다는 결말이었습니다. 참고 : https://stackoverflow.com/questions/15450519/why-does-string-replace-not-work/15450539 test =test.replace("KP", "");  replace 후에 담아 주지 않으면 적용이 안 됩니다!

개발 공부 - OracleXETNSListener 서비스가 로컬 컴퓨터에서 시작했다가 중지되었습니다.

여러 가지 요인이 있지만 PC 이름 변경시 OracleXETNSListener 서비스 시작이 불가능합니다. 고치는 법은 C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN 와 같은 설치 경로에서 listener.ora와 tnsnames.ora 의 pc명을 바꾼 PC명으로 바꿔주면 됩니다. 그래도 안 된다면 cmd 창에서 services.msc 를 입력 후 OracleXETNSListener 서비스를 시작 시키면 됩니다. 오류명: OracleXETNSListener 서비스가 로컬 컴퓨터에서 시작했다가 중지되었습니다. 일부 서비스는 다른 서비스 또는 프로그램에서 사용되지 않으면 자동으로 중지됩니다. 참고한 사이트들 1. http://blog.naver.com/visioner7/120165951652 2. http://database.sarang.net/?inc=read&aid=6819&criteria=oracle&subcrit=&id=&limit=20&keyword=ora-12560&page=5 이런 걸 보면 오라클은 앙칼진 시골 아가씨야