今天同事向我询问图片压缩的算法。我想起大概两三年前做过的一个项目。

当中包括了尺寸和质量两种压缩算法。而且支持JPEG、bmp、PNG等格式。

今天把这段逻辑贴出来,供大家參考。(转载请指明来源于breaksoftware的CSDN博客)

  • 尺寸压缩
bool CompressImagePixel(
const WCHAR* pszOriFilePath,
const WCHAR* pszDestFilePah,
UINT ulNewHeigth,
UINT ulNewWidth )
{
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Status stat = GenericError;
stat = GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );
if ( Ok != stat ) {
return false;
}
// 重置状态
stat = GenericError; // Get an image from the disk.
Image* pImage = new Image(pszOriFilePath); do {
if ( NULL == pImage ) {
break;
} // 获取长宽
UINT unOriHeight = pImage->GetHeight();
UINT unOriWidth = pImage->GetWidth(); do {
CLSID encoderClsid;
if ( unOriWidth < 1 || unOriHeight < 1 ) {
break;
} // Get the CLSID of the JPEG encoder.
if ( !GetEncoderClsid(L"image/jpeg", &encoderClsid) ) {
break;
} REAL fSrcX = 0.0f;
REAL fSrcY = 0.0f;
REAL fSrcWidth = (REAL) unOriWidth;
REAL fSrcHeight = (REAL) unOriHeight ;
RectF RectDest( 0.0f, 0.0f, (REAL)ulNewWidth, (REAL)ulNewHeigth); Bitmap* pTempBitmap = new Bitmap( ulNewWidth, ulNewHeigth );
Graphics* graphics = NULL; do {
if ( !pTempBitmap ) {
break;
} graphics = Graphics::FromImage( pTempBitmap );
if ( !graphics ) {
break;
} stat = graphics->SetInterpolationMode(Gdiplus::InterpolationModeHighQuality);
if ( Ok != stat ) {
break;
} stat = graphics->SetSmoothingMode(Gdiplus::SmoothingModeHighQuality);
if ( Ok != stat ) {
break;
} stat = graphics->DrawImage( pImage, RectDest, fSrcX, fSrcY, fSrcWidth, fSrcHeight,
UnitPixel, NULL, NULL, NULL);
if ( Ok != stat ) {
break;
} stat = pTempBitmap->Save( pszDestFilePah, &encoderClsid, NULL );
if ( Ok != stat ) {
break;
} } while(0); if ( NULL != graphics ) {
delete graphics;
graphics = NULL;
} if ( NULL != pTempBitmap ) {
delete pTempBitmap;
pTempBitmap = NULL;
}
} while(0);
} while (0); if ( pImage ) {
delete pImage;
pImage = NULL;
} GdiplusShutdown(gdiplusToken); return ( ( Ok == stat ) ? true : false );
}
  • 质量压缩
bool CompressImageQuality(
const WCHAR* pszOriFilePath,
const WCHAR* pszDestFilePah,
ULONG quality )
{
// copy from http://msdn.microsoft.com/en-us/library/ms533844(v=VS.85).aspx
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Status stat = GenericError;
stat = GdiplusStartup( &gdiplusToken, &gdiplusStartupInput, NULL );
if ( Ok != stat ) {
return false;
} // 重置状态
stat = GenericError; // Get an image from the disk.
Image* pImage = new Image(pszOriFilePath); do {
if ( NULL == pImage ) {
break;
} // 获取长宽
UINT ulHeight = pImage->GetHeight();
UINT ulWidth = pImage->GetWidth();
if ( ulWidth < 1 || ulHeight < 1 ) {
break;
} // Get the CLSID of the JPEG encoder.
CLSID encoderClsid;
if ( !GetEncoderClsid(L"image/jpeg", &encoderClsid) ) {
break;
} // The one EncoderParameter object has an array of values.
// In this case, there is only one value (of type ULONG)
// in the array. We will let this value vary from 0 to 100.
EncoderParameters encoderParameters;
encoderParameters.Count = 1;
encoderParameters.Parameter[0].Guid = EncoderQuality;
encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
encoderParameters.Parameter[0].NumberOfValues = 1;
encoderParameters.Parameter[0].Value = &quality;
stat = pImage->Save(pszDestFilePah, &encoderClsid, &encoderParameters);
} while(0); if ( pImage ) {
delete pImage;
pImage = NULL;
} GdiplusShutdown(gdiplusToken); return ( ( stat == Ok ) ? true : false );
}

这两个算法,都关联了一个函数GetEncoderClsid,事实上现是:

#include <Windows.h>
#include <GdiPlus.h>
#pragma comment( lib, "GdiPlus.lib" )
using namespace Gdiplus; bool GetEncoderClsid(const WCHAR* pszFormat, CLSID* pClsid)
{
UINT unNum = 0; // number of image encoders
UINT unSize = 0; // size of the image encoder array in bytes ImageCodecInfo* pImageCodecInfo = NULL; // How many encoders are there?
// How big (in bytes) is the array of all ImageCodecInfo objects?
GetImageEncodersSize( &unNum, &unSize );
if ( 0 == unSize ) {
return false; // Failure
} // Create a buffer large enough to hold the array of ImageCodecInfo
// objects that will be returned by GetImageEncoders.
pImageCodecInfo = (ImageCodecInfo*)( malloc(unSize) );
if ( !pImageCodecInfo ) {
return false; // Failure
} // GetImageEncoders creates an array of ImageCodecInfo objects
// and copies that array into a previously allocated buffer.
// The third argument, imageCodecInfos, is a pointer to that buffer.
GetImageEncoders( unNum, unSize, pImageCodecInfo ); for ( UINT j = 0; j < unNum; ++j ) {
if ( wcscmp( pImageCodecInfo[j].MimeType, pszFormat ) == 0 ) {
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
pImageCodecInfo = NULL;
return true; // Success
}
} free( pImageCodecInfo );
pImageCodecInfo = NULL;
return false; // Failure
}

在我的測试代码中,文件名称中包括A的为源文件,文件名称中包括B的是尺寸压缩算法得到的文件,文件名称中包括C的是质量压缩(尺寸不变)算法得到的文件。測试代码是

int _tmain(int argc, _TCHAR* argv[])
{
CompressImagePixel( L"1A.jpg", L"1B.jpg", 100, 100 );
CompressImageQuality( L"1A.jpg", L"1C.jpg", 30 ); CompressImagePixel( L"2A.png", L"2B.jpg", 100, 100 );
CompressImageQuality( L"2A.png", L"2C.jpg", 30 ); CompressImagePixel( L"3A.bmp", L"3B.jpg", 100, 100 );
CompressImageQuality( L"3A.bmp", L"3C.jpg", 30 );
return 0;
}

其压缩结果是





        从压缩结果看。尺寸压缩是稳定的。质量压缩是不稳定的。假设想通过压缩算法控制文件大小,须要结合这两种方法。可是须要指出的是。该质量压缩算法不能够滥用。由于在一定情况下,该质量压缩会使文件空间大小变大。

最后附上project代码。

一种使用GDI+对图片尺寸和质量的压缩方法的更多相关文章

  1. Xamarin设备相关图片尺寸要求

    Xamarin设备相关图片尺寸要求   Xamarin跨平台开发,要兼顾iOS.Android.尤其是图片方面,各个平台有对应的不同要求.在iOS中,需要提供没有后缀(设备无关单位尺寸).@2x(双倍 ...

  2. 大屏iPhone的适配 +iOS 图片尺寸要求

    摘自:http://blog.ibireme.com/2014/09/16/adapted_to_iphone6/ 苹果公司官网设计介绍到:Retina显示屏的超高像素密度已超过人眼能分辨的范围.Re ...

  3. OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放

    这篇已经写得很好,真心给作者点个赞.题目都是直接转过来的,直接去看吧. Reference Link : http://blog.csdn.net/poem_qianmo/article/detail ...

  4. 【OpenCV新手教程之十三】OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔与图片尺寸缩放

    本系列文章由@浅墨_毛星云 出品,转载请注明出处. 文章链接:http://blog.csdn.net/poem_qianmo/article/details/26157633 作者:毛星云(浅墨) ...

  5. 学习 opencv---(12)OpenCV 图像金字塔:高斯金字塔,拉普拉斯金字塔与图片尺寸缩放

    在这篇文章里,我们一起学习下 图像金字塔 的一些基本概念,如何使用OpenCV函数pyrUp和pyrDown 对图像进行向上和向下采样,以及了解专门用于缩放图像尺寸的resize函数的用法.此博文一共 ...

  6. opencv 4 图像处理(漫水填充,图像金字塔与图片尺寸缩放,阈(yu)值化)

    漫水填充 实现漫水填充算法:floodFill函数 简单调用范例 #include <opencv2/opencv.hpp> #include <opencv2/imgproc/im ...

  7. springmvc处理上传图片代码(校验图片尺寸、图片大小)

    package com.maizuo.web.controller; import com.maizuo.domain.Result; import com.maizuo.util.Constants ...

  8. iOS 图片大小压缩 图片尺寸处理

    图片的压缩其实是俩概念,1.是 “压” 文件体积变小,但是像素数不变,长宽尺寸不变,那么质量可能下降,2.是 “缩” 文件的尺寸变小,也就是像素数减少.长宽尺寸变小,文件体积同样会减小. 这个 UII ...

  9. PHPThumb处理图片,生成缩略图,图片尺寸调整,图片截取,图片加水印,图片旋转

    [强烈推荐]下载地址(github.com/masterexploder/PHPThumb). 注意这个类库有一个重名的叫phpThumb,只是大小写的差别,所以查找文档的时候千万注意. 在网站建设过 ...

随机推荐

  1. Hibernate的基础入门(一)

    一Java三层结构 1 web层:struts框架 2 service层:Spring框架 3  dao层 :hibernate框架 相当于MVC的思想 1 M:模型èhibernate框架 2 V: ...

  2. 基于node的websocket示例

    websocket:用语服务器端主动向客户端推送消息 本例基于koa框架编写用例:服务器端需要安装相关模块 koa koa-socket co等 服务器端脚本:(需要安装相关模块 koa koa-so ...

  3. Object.observe() 观察对象

    这个对象方法可以用来异步观察对javascript对象的改动: // Let's say we have a model with data var model = {};   // Which we ...

  4. Robotframework自动化系统:筛选结果数量统计

    Robotframework自动化系统:筛选结果数量统计 上一个节点已经可以随机选中某一个下拉框的值,我们在使用evaluate随机数的时候需要计算下拉选项总数,这时候我们是手工计算输入的:这时候如果 ...

  5. [java基础] java 左移和右移

    今天搜到一个比较好用的在线编译器,希望和大家分享. 除了java还有c++....,地址是http://www.tutorialspoint.com/compile_java_online.php 另 ...

  6. Input类型是checkbox时checked属性获取

    记录一下checkbox 的 checked 属性的获取办法,以备忘记: 假如你的一个HTML页中有这么一段代码: <input name="chbRem" id=" ...

  7. 解决autocad闪退

    1.进入注册表,regedit 2.找到ROOT\installer\Products ,找到以7D2F开头的键值,这里有两个都得删除 3.删除programdata目录下的AutoDesk目录,及f ...

  8. wkt转换geojson

    应用配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.o ...

  9. 70、django之Ajax初识

    Ajax准么说是用于Javascript与服务器端进行交互的,我们之前呢没有了解ajax也同样可以完成与服务器的交互,那么ajax的优势在哪里?首先ajax是异步交互的也就是说我们基本不会遇到卡顿现象 ...

  10. sql: 左连接 和内连接区别联系

    select * from (select rowtemp.*, rownum rownumtemp from (select u.*, UA.USR_INFO_ID USR_INFO_ID, UA. ...