c++基于CImage实现图片格式转换完整源代码

最近遇到项目需要,对图片进行格式转换,抱着怎么简单怎么做的想法,于是进行了验证,代码参考自网络,进行了简单的修改。

我这里提供完整的代码。

c++基于CImage实现图片格式转换完整源代码_第1张图片

直接上代码:

头文件:

#pragma once

#include 
#include 
#include 

#ifdef DLLIMPORT
#define _DLL_DECLARE_ __declspec(dllimport)
#else
#define _DLL_DECLARE_ __declspec(dllexport)
#endif

_DLL_DECLARE_ int testLocalCode();

// 获取夹具类型
_DLL_DECLARE_ bool ConvertImage(std::string sSrcImgPath, std::string sDstImgPath);

实现文件:

#include "stdafx.h"

#include "atlimage.h"
#include "ImageFormatConventor.h"

_DLL_DECLARE_ int testLocalCode()
{

    return 0;
}

_DLL_DECLARE_ bool ConvertImage(std::string sSrcImgPath, std::string sDstImgPath)
{
	CString strSrcFile(sSrcImgPath.c_str());
	CString strDstFile(sDstImgPath.c_str());
    // 根据目标文件的后缀确定要转换成的目标文件类型
    // 使用CImage实现不同格式图片文件的转换
    if (strDstFile.IsEmpty())
    {
        return FALSE;
    }

    CImage img;
    HRESULT hResult = img.Load(strSrcFile); // 加载源图片文件
    if (hResult != S_OK)
    {
        return FALSE;
    }

    GUID guidFileType = Gdiplus::ImageFormatPNG; // 默认保存为png图片
    CString strExt;
    int nIndex = strDstFile.ReverseFind(_T('.'));
    if (nIndex != -1)
    {
        strExt = strDstFile.Right(strDstFile.GetLength() - nIndex - 1);
        if (strExt == _T("png"))
        {
            guidFileType = Gdiplus::ImageFormatPNG;
        }
        else if (strExt == _T("jpg"))
        {
            guidFileType = Gdiplus::ImageFormatJPEG;
        }
        else if (strExt == _T("bmp"))
        {
            guidFileType = Gdiplus::ImageFormatBMP;
        }
        else if (strExt == _T("gif"))
        {
            guidFileType = Gdiplus::ImageFormatGIF;
        }
        else
        {
            guidFileType = Gdiplus::ImageFormatPNG;
        }
    }

    hResult = img.Save(strDstFile, guidFileType); // 保存为目标文件
    if (hResult != S_OK)
    {
        return FALSE;
    }

    return TRUE;
}

亲测有效,欢迎交流与讨论。

你可能感兴趣的:(c++,MFC,c++,mfc)