Scientia Conditorium
[C++] 이미지 파일 ↔ 바이너리 파일 변환하기 본문
[C++] 이미지 파일 ↔ 바이너리 파일 변환하기
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream image("pop_cat.png", std::ios::in | std::ios::binary);
std::ofstream binary("binary_image_data.txt", std::ios::out | std::ios::binary);
char ch;
while (!image.eof())
{
ch = image.get();
binary.put(ch);
}
std::cout << "Image Succesfully Converted into binary File" << std::endl;
image.close();
binary.close();
std::ifstream binary_input("binary_image_data.txt", std::ios::in | std::ios::binary);
std::ofstream image_result("result.png", std::ios::out | std::ios::binary);
while (!binary_input.eof())
{
ch = binary_input.get();
image_result.put(ch);
}
std::cout << "Converted Binary File into new image" << std::endl;
binary_input.close();
image_result.close();
return 0;
}
코드 출처 : https://youtu.be/2iZu01UHxfE
코드 자체는 단순하다.
변환하고자 하는 이미지 파일을 ifstream에 넣고 get() 함수로 char형만큼 문자 배열로 하나씩 가져온다.
가져온 문자 배열을 바이너리 포맷에 그대로 집어넣는다.
다시 복원하고자 할 때는 입출력을 반대로 진행하면 된다.
다만 파일 크기가 커질경우 느린 단점이 있기 때문에 별로 권장하지는 않는 방법이다.
코드 출처 영상에서는 std::ios::app을 사용하였지만, 동작하지 않아서 std::ios::binary로 바꾸었다.
'프로그래밍 > C++' 카테고리의 다른 글
[CMake] CMake란?! (0) | 2024.06.25 |
---|---|
[C++][Summary] Approaching C++ Safety - Bjarne Stroustrup (0) | 2023.08.23 |
[C++] struct 와 class 의 차이점 (0) | 2022.09.17 |
[C++] 이중 map - map 안에 map 사용하기 (0) | 2022.09.17 |