기본 콘텐츠로 건너뛰기

개발 공부 - [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://www.dvdvideosoft.com/products/dvd/Free-Video-to-JPG-Converter.htm (240826: 다운로드 시 정상적으로 되지 않아서 URL 수정) 일 하면서 듀얼 모니터에 켜 놨는데 속도가 괜찮았다. * Every frame 으로 사용해야 한다. 4) 중복 사진 제거해주는 프로그램을 사용했다. VlsiPics  > http://www.visipics.info/index.php?title=Main_Page 생각보다 느리니 퇴근시에 걸어놓고 가면 된다. 한번 play가 끝나면 Auto-select 하고 Delete 하면 된다. 5) 이미지를 일괄 Crop 작업 해주는 프로그램을 사용했다. JPEGCrops > https://jpegcrops.softonic.kr/ *...

개발 공부 - PC 카카오톡 작업 표시줄 아이콘 이미지 변경 방법

PC 카카오톡 사용시 작업 표시줄에서 아이콘 이미지를 변경하는 방법이다. 1) 작업 표시줄 내 카카오톡 아이콘에서 마우스 오른쪽 버튼을 누른  뒤 속성에 들어간다. 2) 아이콘 변경에서  C:\Windows\system32\imageres.dll C:\Windows\system32\shell32.dll C:\Windows\system32\DDORes.dll C:\Windows\System32\moricons.dll (MS DOS Icons) 등을 누른 뒤 적당한 것을 선택하여 적용한다. * 사내 메신저 아이콘을 참고해도 된다. 참고 : 기본 아이콘 위치 https://blog.silnex.kr/windowstip-windows-%EA%B8%B0%EB%B3%B8-%EC%95%84%EC%9D%B4%EC%BD%98-%EC%9C%84%EC%B9%98/ 2022. 11. 29.  생각보다 유입이 많아서 놀랐습니다. PC 카톡 사용자 화이팅!

운동 정보 - 어메이즈핏 밴드 5 스마트밴드 나이키 런 클럽(NRC = Nike Run Club) 연동

 나이키 런 클럽 쓰려고 산 어메이즈핏 밴드5 인데 연동이 영 어려워서 찾아보고 써봤다. 1. Zepp 앱은 연동이 되어 있어야 한다. 2.  Zepp 앱 -> 프로필 -> 내 기기 -> Amazfit Band 5 3. 검색 가능 : 켜짐 활동 심박수 공유 : 켜짐 연결 제한 : 꺼짐 (기본) 백그라운드에서 실행 : 제외로 등록 4. NRC(나이키 런 클럽) 앱 -> 설정 -> 러닝 설정 -> 기기 5. 심박수 표시 -> 블루투스에서 AmazFit Band 5 누르고 NRC 즐기면 된다! * 안드로이드 이용자입니다.