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

当中包括了尺寸和质量两种压缩算法。而且支持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. Django 模板中 include 标签使用小结

    include 标签允许在模板中包含其它的模板的内容. 标签的参数是所要包含的模板名称,可以是一个变量,也可以是用单/双引号硬编码的字符串. 每当在多个模板中出现相同的代码时,就应该考虑是否要使用 { ...

  2. 【经验分享】Trachtenberg system(特拉亨伯格速算系统)

    二战期间,俄国的数学家Jakow Trachtenberg(1888-1953)被关进纳粹集中营,在狱中,他开发出了一套心算算法,这套算法后来被命名为Trachtenberg(特拉亨伯格)速算系统. ...

  3. Android 开发笔记___SQLite__基本用法

    SQLiteOpenHelper package com.example.alimjan.hello_world.dataBase; import android.content.ContentVal ...

  4. js input输入事件兼容性问题

    if(navigator.userAgent.indexOf('Android') > -1){ $("#sign").on("input", funct ...

  5. HTML5 设备上的API

    一.Vibration API ,接受两种类型参数 vibrate (unsigned long time)   当参数是unsigned long的时候 此时参数表示震动时间.  NotSuppor ...

  6. FTP配置的一些笔记

    1.必须关闭防火墙 iptables -F iptables -X iptables -Z vi /etc/selinux/config          SELINUX=disabled seten ...

  7. JAVA提高十二:HashMap深入分析

    首先想说的是关于HashMap源码的分析园子里面应该有很多,并且都是分析得很不错的文章,但是我还是想写出自己的学习总结,以便加深自己的理解,因此就有了此文,另外因为小孩过来了,因此更新速度可能放缓了, ...

  8. Java钉钉开发_03_通讯录管理之 人员管理 和 部门管理

    一.本节要点 1.通讯录权限 ISV(应用服务商)默认无管理通讯录的权限,企业应用默认有所有通讯录权限. 2.数据传输格式—JSON 请参见: Java_数据交换_fastJSON_01_用法入门 二 ...

  9. 数据库之Oracle——初级

    世上岂无千里马,人中难得九方皋: 酒船鱼网归来是,花落故溪深一篙. 关于数据库的第一篇博客,这是我的第二次,人生第二春,什么也不想说,静静的开始吧,至于为什么写唐诗,请看第一篇文章! Oracle 初 ...

  10. 数组去重+indexOf()应用

    说起数组去重大家都不陌生,去重也有好多种方法,这里介绍很好理解的两种. 第一种 首先说一下第一种的逻辑,就是先拿第一个去跟第二个比,再跟第三个比,再跟第四个比--只要发现有相等的,可以用splice( ...