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

当中包括了尺寸和质量两种压缩算法。而且支持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. sublime中配置Java 环境

    1.线安装jdk,并配置好环境变量2.创建批处理或Bash Shell脚本文件打开任意的文本编辑器,输入下面的内容,并保存为runJava.bat文件,然后把runJava.bat批处理文件移动到JD ...

  2. javascript中toString和valueOf方法的区别

    toString():将对象转为字符串 valueOf():获取对象的原始值, 1.针对基本类型的变量:如在string,number,boolean类型的变量上调用这两个方法时,直接返回原始值,即变 ...

  3. sublime text全程指南【转载】

    前言(Prologue) Sublime Text是一款跨平台代码编辑器(Code Editor),从最初的Sublime Text 1.0,到现在的Sublime Text 3.0,Sublime ...

  4. struts2运行过程(图解)

    .................................................................................................... ...

  5. 全球领先的redis客户端:SFedis

    零.背景 这个客户端起源于我们一个系统的生产问题. 一.问题的发生 在我们的生产环境上发生了两次redis服务端连接数达到上限(我们配置的单节点连接数上限为8000)导致无法创建连接的情况.由于这个系 ...

  6. [Redis源码阅读]sds字符串实现

    初衷 从开始工作就开始使用Redis,也有一段时间了,但都只是停留在使用阶段,没有往更深的角度探索,每次想读源码都止步在阅读书籍上,因为看完书很快又忘了,这次逼自己先读代码.因为个人觉得写作需要阅读文 ...

  7. linux操作系统基础篇(六)

    linux服务篇 1.samba服务的搭建 samba的功能: samba是一个网络服务器,用于Linux和Windows之间共享文件.2. samba服务的启动.停止.重启service smb s ...

  8. Cache类缓存

    此处主要总结System.Web.Caching.Cache类 该类是用于存储常用信息的类,HttpRuntime.Cache以及HttpContext.Current.Cache都是该类的实例. 该 ...

  9. LKD: Chapter 7 Interrupts and Interrupt Handlers

    Recently I realized my English is still far from good. So in order to improve my English, I must not ...

  10. LSF-SCNN:一种基于 CNN 的短文本表达模型及相似度计算的全新优化模型

    欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 本篇文章是我在读期间,对自然语言处理中的文本相似度问题研究取得的一点小成果.如果你对自然语言处理 (natural language proc ...