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

当中包括了尺寸和质量两种压缩算法。而且支持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. touch pointer

    在早期的浏览器,输入的事件其实相对单纯,只有考虑到鼠标和键盘两种:而当时的鼠标事件,其实就是 click.mousedown.mouseup 等等的事件.但是当手机.平板开始流行时候,再移动装置上的主 ...

  2. [html5] 初识绘图canvas

    这个星期被调到别的项目组专门做了一会儿前端,没办法,人太少,我也只能硬着头皮上... 说起来,html5的canvas真的好用,可以画色块,可以嵌入图片,可以通过定位在图片上写字等等 举例如下 在ht ...

  3. EF动态拼接查询

    1.业务中遇到个问题,需要查询如某表的id为1或者2或者3,这里是根据传递参数获取如:传递1,2或者1,3或者1,2,3这里在sql中很好拼接如下: or id= or name=3//3代表另一个字 ...

  4. mkdir--命令

    mkdir命令 mkdir:make directory(ies)的缩写,用来创建目录 1.语法 mkdir [OPTION]... DIRECTORY 注释:option是选择,可选,directo ...

  5. Mybatis面试整理

    #{}和${}的区别 #{}是预编译处理,${}是字符串替换. Mybatis在处理#{}时,会将sql中的#{}替换为?号,调用PreparedStatement的set方法来赋值: Mybatis ...

  6. 动态加载js css 插件

    简介 动态加载js,css在现在以及将来肯定是很重要的.目前来看前端代码编写的业务量已经远远超过后端编写的.随着对用户体验度逐渐增强,前端业务复杂,加载速度变得很慢很慢.为了解决这个问题,目前出现的两 ...

  7. Leetcode刷题

    Leetcode题库       本博客用于记录在LeetCode网站上一些题的解答方法.具体实现方法纯属个人的一些解答,这些解答可能不是好的解答方法,记录在此,督促自己多学习多练习.     The ...

  8. 设计模式的征途—9.组合(Composite)模式

    树形结构在软件中随处可见,比如操作系统中的目录结构,公司组织结构等等,如何运用面向对象的方式来处理这种树形结构是组合模式需要解决的问题.组合模式通过一种巧妙的设计方案来使得用户可以一致性地处理整个树形 ...

  9. Python PycURL 网络编程

    http://blog.chinaunix.net/uid-20544356-id-290882.html 在使用urllib的时候经常会死掉,以前debug过,是没有设置 timing out 所以 ...

  10. Spring Boot中采用Mockito来mock所测试的类的依赖(避免加载spring bean,避免启动服务器)

    最近试用了一下Mockito,感觉真的挺方便的.举几个应用实例: 1,需要测试的service中注入的有一个dao,而我并不需要去测试这个dao的逻辑,只需要对service进行测试.这个时候怎么办呢 ...