자기개발/C++
C++(mfc) - 1채널 이미지를 3채널 이미지로 변환후 사각형그리고 저장
pi92
2021. 9. 17. 11:06
#define _AFXDLL
#include <afxwin.h>
#include <atlimage.h>
#include <iostream>
using namespace std;
void point_swat(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int w = 120;
int h = 100;
//Make Gray image(1BYTE)
LPBYTE grayBits = nullptr;
grayBits = new BYTE[w * h];
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
grayBits[i*w + j] = 255 - (double)255 * j / (w - 1);
}
}
//gray를 컬러 이미지(3BYTE)로
LPBYTE colorBits = nullptr;
colorBits = new BYTE[w * h * 3];
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
colorBits[i * 3 * w + 3 * j] = grayBits[i*w + j];
colorBits[i * 3 * w + 3 * j + 1] = grayBits[i*w + j];
colorBits[i * 3 * w + 3 * j + 2] = grayBits[i*w + j];
}
}
//컬러로 옮겨준 후 메모리 삭제
delete[] grayBits;
grayBits = nullptr;
//colorBits 에 빨간색 사각형 넣기
int start_x = 30, start_y = 30, end_x = 66, end_y = 60;
if (start_x < 0 || start_x > w || end_x < 0 || end_x > w || start_y < 0 || start_y > h || end_y < 0 || end_y > h)
{
cout << " 사각형 영역이 잘못 그려 졌습니다." << endl;
return 0;
}
if (start_x > end_x) point_swat(&start_x, &end_x);
if (start_y > end_y) point_swat(&start_y, &end_y);
//사각형 채워서 그리기
//for (int i = start_y; i < end_y+1; i++)
//{
// for (int j = start_x; j < end_x+1; j++)
// {
// colorBits[i * w * 3 + 3*j] = 0;
// colorBits[i * w * 3 + 3*j + 1] = 0;
// colorBits[i * w * 3 + 3*j + 2] = 255;
// }
//}
//사각형 세로 그리기
for (int i = start_y; i < end_y + 1; i++)
{
colorBits[i * w * 3 + 3 * start_x] = 0;
colorBits[i * w * 3 + 3 * start_x + 1] = 0;
colorBits[i * w * 3 + 3 * start_x + 2] = 255;
colorBits[i * w * 3 + 3 * end_x] = 0;
colorBits[i * w * 3 + 3 * end_x + 1] = 0;
colorBits[i * w * 3 + 3 * end_x + 2] = 255;
}
//사각형 가로 그리기
for (int j = start_x; j < end_x + 1; j++)
{
colorBits[start_y * w * 3 + 3 * j] = 0;
colorBits[start_y * w * 3 + 3 * j + 1] = 0;
colorBits[start_y * w * 3 + 3 * j + 2] = 255;
colorBits[end_y * w * 3 + 3 * j] = 0;
colorBits[end_y * w * 3 + 3 * j + 1] = 0;
colorBits[end_y * w * 3 + 3 * j + 2] = 255;
}
//이미지 저장할 CImage 변수 생성
CImage image;
image.Create(w, h, 24);
RGBQUAD rgbQuad[256];
for (int i = 0; i < 256; i++) {
rgbQuad[i] = { BYTE(i),BYTE(i),BYTE(i),0 };
}
//image.SetColorTable(0, 255, rgbQuad);
//image에 colorBits 데이터값 넣기
LPBYTE m_pBits = (LPBYTE)image.GetBits();
for (int i = 0; i < h; i++) {
LPBYTE pRow = m_pBits + (i*image.GetPitch());
memcpy(pRow, colorBits + (i*w * 3), w * 3);
}
CreateDirectory(_T("save"), NULL);
image.Save(_T("save/temp.bmp"));
image.Destroy();
//colorBits 해제
delete[] colorBits;
colorBits = nullptr;
_CrtDumpMemoryLeaks();
return 0;
}