Scientia Conditorium

[C++] 이미지 파일 ↔ 바이너리 파일 변환하기 본문

프로그래밍/C++

[C++] 이미지 파일 ↔ 바이너리 파일 변환하기

크썸 2022. 9. 9. 15:41

[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로 바꾸었다.