TIF圖像目標物理尺寸及DPI修改

#include <iostream>
#include <Windows.h>
#include <gdiplus.h>

#pragma comment(lib,"Gdiplus.lib")
using namespace Gdiplus;
using namespace std;
/*
 *	通過字符串獲得對應的CLSID,也就是圖像編碼器位置
 *	format:圖像格式,如:image/bmp
 *	pClsid:存放對應的CLSID
 *	成功返回對應的編碼器位置,失敗返回-1.
 */
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
	UINT  num = 0;          //圖像編碼器數量
	UINT  size = 0;         //圖像編碼器數組大小

	ImageCodecInfo* pImageCodecInfo = NULL;
	GetImageEncodersSize(&num, &size);//獲取編碼器數量
	if (size == 0)
		return -1;
	pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
	if (pImageCodecInfo == NULL)
		return -1;
	GetImageEncoders(num, size, pImageCodecInfo);//獲取本機支持的編碼器
	for (UINT j = 0; j < num; ++j)
	{
		if (wcscmp(pImageCodecInfo[j].MimeType, format) == 0)//找到該格式就將對應的CLSID給*pClsid
		{
			*pClsid = pImageCodecInfo[j].Clsid;
			free(pImageCodecInfo);
			return j;
		}
	}
	free(pImageCodecInfo);
	return -1;
}

int main(void)
{
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	// GDI+的任何操作之前應該先初始化
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
	// 載入圖片
	Image* image = new Image(L"原圖像\\Fig.7.tif");
	double paperW = 19;//圖片紙張寬度要求
	int dpi = 500;//DPI值設置
	//計算設置DPI對應圖像像素
	int srcH = image->GetHeight();
	int srcW = image->GetWidth();
	int destWidth = int(paperW/2.54*dpi);//1英寸=2.54釐米,Dpi=像素除以英寸
	int destHeight = int(srcH / (double)srcW * destWidth);
	//對模板圖像DPI進行設置,並將原圖像拉伸放到目標圖像中
	Bitmap* pDestBmp = new Bitmap(destWidth, destHeight, PixelFormat24bppRGB);
	pDestBmp->SetResolution(dpi, dpi);//設置DPI
	Graphics* g = Graphics::FromImage(pDestBmp);
	g->SetInterpolationMode(InterpolationModeHighQualityBicubic);//設置圖像拉伸算法爲高保真算法
	g->DrawImage(image, 0, 0, destWidth, destHeight);//將圖像像素縮放到要求狀態
	CLSID  encoderClsid;
	// 獲取要存儲格式的圖像編碼器位置
	GetEncoderClsid(L"image/tiff", &encoderClsid);
	// 存儲圖像
	if (Ok != pDestBmp->Save(L"修改圖像\\Fig.2.tif", &encoderClsid, NULL))
	{
		printf("圖像保存失敗\n");
	}
	//釋放對象
	delete image;
	delete pDestBmp;
	printf("圖片:Fig.7.tif 轉換完成\n");
	// 關閉GDI+
	GdiplusShutdown(gdiplusToken);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章