过年回家,走之前留一个用GDI+实现的略缩图控件

这是一个加载文件夹图片略缩图的控件,支持多种图片格式~~用法也比较简单
图片
(1)、源代码

//头文件ListImageCtrl.h 
#pragma once
#include <vector>

//note:need GDI+

// ListImageCtrl.h : header file

class CListImageCtrl : public CListCtrl
{
// Construction
public:
CListImageCtrl();

// Attributes
public:
void CreateColumn();
//
BOOL  GetImageFileNames();// gather the image file names
void  DrawThumbnails();// draw the thumbnails in list control
void  Load();         //start load files
void Clear();   //clear list

// Operations
public:
CStringm_strImageDir;
CImageListm_ImageListThumb;// image list holding the thumbnails
std::vector<CString> m_VectorImageNames;// vector holding the image names
intm_nSelectedItem;
BOOL  m_bHorz;

// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CListImageCtrl)
//}}AFX_VIRTUAL

// Implementation
public:
virtual ~CListImageCtrl();

// Generated message map functions
protected:
//{{AFX_MSG(CListImageCtrl)
afx_msg void OnDropFiles(HDROP hDropInfo);
//}}AFX_MSG

DECLARE_MESSAGE_MAP()
};

// ListImageCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "Medical.h"
#include "ListImageCtrl.h"

#define THUMBNAIL_WIDTH  90
#define THUMBNAIL_HEIGHT 90

void DoEvents(void);

/
// CListImageCtrl

CListImageCtrl::CListImageCtrl()
{
m_strImageDir = _T("");
m_bHorz = FALSE;
}

CListImageCtrl::~CListImageCtrl()
{
}


BEGIN_MESSAGE_MAP(CListImageCtrl, CListCtrl)
//{{AFX_MSG_MAP(CListImageCtrl)
ON_WM_DROPFILES()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/
// CListImageCtrl message handlers

// This funtion is used to load the Window dropped files into the listview

void CListImageCtrl::OnDropFiles(HDROP hDropInfo) 
{
WORD wNumFilesDropped = DragQueryFile(hDropInfo, -1, NULL, 0);

CString firstFile(_T(""));
int kk=0;
int tTot=(int)wNumFilesDropped;

// show hour glass cursor
BeginWaitCursor();

for (WORD x = 0 ; x < wNumFilesDropped; x++) 
{
kk++;
// Get the number of bytes required by the file's full pathname
WORD wPathnameSize = DragQueryFile(hDropInfo, x, NULL, 0);
TRACE1("wPathnameSize=%d,\n",wPathnameSize);

// Allocate memory to contain full pathname & zero byte
wPathnameSize +=1;
TCHAR * npszFile = (TCHAR *) LocalAlloc(LPTR, sizeof(TCHAR)*wPathnameSize);  //注意分配的内存大小

// If not enough memory, skip this one
if (npszFile == NULL) continue;
DragQueryFile(hDropInfo, x, npszFile, wPathnameSize);

if (firstFile=="") 
firstFile=npszFile;

CString strExt;
CString nFileText;
CString pItemText=npszFile;

TRACE1("%s\n",pItemText);

int i=pItemText.ReverseFind('\\');
nFileText = pItemText.Mid(i+1); 
m_strImageDir = pItemText.Left(i+1);

strExt = pItemText.Right(3);
TRACE1("strExt=%s\n",strExt);

if ( (strExt.CompareNoCase( TEXT("bmp") ) == 0) ||
(strExt.CompareNoCase( TEXT("jpg") ) == 0) ||
(strExt.CompareNoCase( TEXT("gif") ) == 0) ||
(strExt.CompareNoCase( TEXT("tif") ) == 0) ||
(strExt.CompareNoCase( TEXT("png") ) == 0) )
{
// save the image file name, not the path
m_VectorImageNames.push_back(nFileText);  
}

// clean up
LocalFree(npszFile);
}

// Free the memory block containing the dropped-file information
DragFinish(hDropInfo);

if(!m_VectorImageNames.empty())
DrawThumbnails();

SetFocus();
SetItemState(0, LVIS_SELECTED |    LVS_ICON | LVS_AUTOARRANGE, LVIS_SELECTED | LVIS_FOCUSED | LVIS_ACTIVATING); 
EndWaitCursor();

CListCtrl::OnDropFiles(hDropInfo);
}


void CListImageCtrl::CreateColumn()
{
InsertColumn(0,_T("Filename"),LVCFMT_LEFT,125,-1);
InsertColumn(1,_T("Path"),LVCFMT_LEFT,125,-1);
InsertColumn(2,_T("Size"),LVCFMT_LEFT,75,-1);

HIMAGELIST hScreens = ImageList_Create(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, ILC_COLOR32 /*| ILC_MASK*/ , 0, 1);
m_ImageListThumb.Attach(hScreens);
m_nSelectedItem = 0;

// load the starting bitmap ("Loading..." and "Corrupt file")
//  CBitmap dummy;
//  dummy.LoadBitmap(IDB_BITMAP1);
//  m_ImageListThumb.Add(&dummy, RGB(0, 0, 0));

SetImageList(&m_ImageListThumb, LVSIL_NORMAL);
SetImageList(&m_ImageListThumb, LVSIL_SMALL);

}

// this function is used to enable the system messages
// this is mainly used to display the multiple images dropped on the list control

void DoEvents(void)
{
    MSG Symsg;
    
    while(PeekMessage(&Symsg,NULL,0,0,PM_REMOVE))
    {
    TranslateMessage(&Symsg);
    DispatchMessage(&Symsg);
    }
}

BOOL  CListImageCtrl::GetImageFileNames()
{
CStringstrExt;
CStringstrName;
CStringstrPattern;
BOOLbRC = TRUE;

HANDLEhFind = NULL;
WIN32_FIND_DATAFindFileData;
std::vector<CString>VectorImageNames;

if ( m_strImageDir[m_strImageDir.GetLength() - 1] == TCHAR('\\') )
strPattern.Format( TEXT("%s*.*"), m_strImageDir );
else
strPattern.Format( TEXT("%s\\*.*"), m_strImageDir );

hFind = ::FindFirstFile(strPattern, &FindFileData);// strat search
if (hFind == INVALID_HANDLE_VALUE)
{
LPVOID  msg;
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 
NULL, 
GetLastError(), 
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&msg, 
0, 
NULL);
MessageBox((LPTSTR)msg, CString((LPCSTR)IDS_TITLE), MB_OK|MB_ICONSTOP);
::LocalFree(msg);
return FALSE;
}

// filter off the system files and directories
if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)  &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)     &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)     &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY))
{    
// test file extension
strName = FindFileData.cFileName;
strExt = strName.Right(3);

if ( (strExt.CompareNoCase( TEXT("bmp") ) == 0) ||
(strExt.CompareNoCase( TEXT("jpg") ) == 0) ||
(strExt.CompareNoCase( TEXT("gif") ) == 0) ||
(strExt.CompareNoCase( TEXT("tif") ) == 0) ||
(strExt.CompareNoCase( TEXT("png") ) == 0) )
{
// save the image file name
VectorImageNames.push_back(strName);
}
}  

// loop through to add all of them to our vector
while (bRC)
{
bRC = ::FindNextFile(hFind, &FindFileData);
if (bRC)
{
// filter off the system files and directories
if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)  &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)     &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)     &&
!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY))
{
// test file extension
strName = FindFileData.cFileName;
strExt = strName.Right(3);

if ( (strExt.CompareNoCase( TEXT("bmp") ) == 0) ||
(strExt.CompareNoCase( TEXT("jpg") ) == 0) ||
(strExt.CompareNoCase( TEXT("gif") ) == 0) ||
(strExt.CompareNoCase( TEXT("tif") ) == 0) ||
(strExt.CompareNoCase( TEXT("png") ) == 0) )
{
// save the image file name
VectorImageNames.push_back(strName);
}
}
}  
else
{
DWORD err = ::GetLastError();
if (err !=  ERROR_NO_MORE_FILES)
{
LPVOID msg;
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 
NULL, err, 
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&msg, 0, NULL);
MessageBox((LPTSTR)msg, CString((LPCSTR)IDS_TITLE), MB_OK|MB_ICONSTOP);
::LocalFree(msg);
::FindClose(hFind);
return FALSE;
}
}
} // end of while loop

// close the search handle
::FindClose(hFind);

// update the names, if any
if ( !VectorImageNames.empty() )
{
// reset the image name vector
m_VectorImageNames.clear();
m_VectorImageNames = VectorImageNames;
return TRUE;
}

return FALSE;
}

void  CListImageCtrl::DrawThumbnails()
{
CStringstrPath;
inti;

// no images
if (m_VectorImageNames.empty())
return;

// set the length of the space between thumbnails
// you can also calculate and set it based on the length of your list control
int nGap = 40;

// hold the window update to avoid flicking
SetRedraw(FALSE);

// reset our image list
for (i = 0; i < m_ImageListThumb.GetImageCount(); i++)
m_ImageListThumb.Remove(i);

// remove all items from list view
if (this->GetItemCount() != 0)
this->DeleteAllItems();

// set the size of the image list
m_ImageListThumb.SetImageCount(m_VectorImageNames.size());
i = 0;

// draw the thumbnails
std::vector<CString>::iterator  iter;
for (iter = m_VectorImageNames.begin(); iter != m_VectorImageNames.end(); iter++)
{
HBITMAP hbmReturn = NULL; 
Bitmap  *bmPhoto  = NULL;
CBitmap Bmp1;

// load the bitmap
strPath.Format( TEXT("%s\\%s"), m_strImageDir, *iter );

Bitmap img( strPath.AllocSysString() );

int sourceWidth  = img.GetWidth();
int sourceHeight = img.GetHeight();

int destX, destY, destWidth, destHeight;
const float fRatio=(float)THUMBNAIL_HEIGHT/THUMBNAIL_WIDTH;
const float fImgRatio=(float)sourceHeight/sourceWidth;

if(fImgRatio > fRatio)
{
destWidth=(THUMBNAIL_HEIGHT/fImgRatio);
destX=(THUMBNAIL_WIDTH-destWidth)/2;
destY=0;
destHeight=THUMBNAIL_HEIGHT;
}
else
{
destX=0;
destWidth=THUMBNAIL_WIDTH;
destHeight=(THUMBNAIL_WIDTH*fImgRatio);
destY=(THUMBNAIL_HEIGHT-destHeight)/2;
}

//check out very small image
if ((sourceHeight < THUMBNAIL_HEIGHT) && (sourceWidth < THUMBNAIL_WIDTH))
{
destWidth=sourceWidth;
destHeight=sourceHeight;
destX=(THUMBNAIL_WIDTH-destWidth)/2;
destY=(THUMBNAIL_HEIGHT-destHeight)/2;
}

bmPhoto = new Bitmap( THUMBNAIL_WIDTH, THUMBNAIL_WIDTH , PixelFormat32bppRGB );
bmPhoto->SetResolution( img.GetHorizontalResolution(), img.GetVerticalResolution() );

Graphics *grPhoto = Graphics::FromImage( bmPhoto );
Color colorW(255, 255, 255, 255);
Gdiplus::Pen pen(Color(200,192,192,192));
grPhoto->Clear( colorW );
grPhoto->SetInterpolationMode( InterpolationModeHighQualityBilinear );
grPhoto->DrawImage( &img, Rect(destX, destY, destWidth, destHeight) );
grPhoto->DrawRectangle(&pen,Gdiplus::Rect(0,0,THUMBNAIL_WIDTH-1,THUMBNAIL_HEIGHT-1));  //draw border

bmPhoto->GetHBITMAP( colorW, &hbmReturn );

Bmp1.Attach( hbmReturn );
m_ImageListThumb.Replace( i, &Bmp1, NULL );
//int imgP=m_ImageListThumb.Add(&Bmp1,RGB(0,0,0));

InsertItem(i, m_VectorImageNames[i],i);  //Link to the added listview item 

delete grPhoto;
delete bmPhoto;
Bmp1.Detach();
DeleteObject( hbmReturn );
i++;

}

// let's show the new thumbnails
SetRedraw(); 
}

void CListImageCtrl::Load() 
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);

// validate image directory
if (m_strImageDir.IsEmpty())
{
MessageBox(CString((LPCSTR)IDS_DIR_ERROR), CString((LPCSTR)IDS_TITLE), MB_OK|MB_ICONSTOP);
return;
}

// show hour glass cursor
BeginWaitCursor();

// get the names of bitmap files
 if ( !GetImageFileNames() )
 {
 EndWaitCursor();
 return;
 }

// draw thumbnail images in list control
DrawThumbnails();

// draw the selected image in its full size
//DrawSelectedImage();

// if this was a shortcut, we need to expand it to the target path
SetItemState(0, LVIS_SELECTED |    LVS_ICON | LVS_AUTOARRANGE, LVIS_SELECTED | LVIS_FOCUSED | LVIS_ACTIVATING); 
SetFocus();

RedrawWindow(NULL,NULL);

EndWaitCursor();

}

void CListImageCtrl::Clear()
{
// hold the window update to avoid flicking
SetRedraw(FALSE);

// reset our image list
for (int i = 0; i < m_ImageListThumb.GetImageCount(); i++)
m_ImageListThumb.Remove(i);

// remove all items from list view
if (this->GetItemCount() != 0)
this->DeleteAllItems();

m_strImageDir = _T("");

m_VectorImageNames.clear();

SetRedraw(); 

}

(2)、用法

1、在界面上放一个ListCtrl控件,设置View属性为ICON,Accept files属性TRUE,然后关联一个变量,如CListImageCtrl  m_lstImg;
2、在 BOOL CXXXDlg::OnInitDialog()初始化控件,一个语句就可以了m_lstImg.CreateColumn();
3、加载略缩图方法可以拖拽图片到控件,也可以这样加载
                        //strPath 是一个CString变量,文件夹路径

m_lstImg.m_strImageDir = strPath;
m_lstImg.Load();

 


 


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/243766.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何避免偶然的锁存器和%0h

如何避免偶然的锁存器和%0h 如果用到if语句&#xff0c;最好写上else项。如果用case语句&#xff0c;最好写上default项。遵循上面两条原则&#xff0c; 就可以避免发生这种错误&#xff0c;使设计者更加明确设计目标&#xff0c;同时也增强了Verilog程序的可读性可以通过在%和…

记住北京历史上的灾难

读《北京灾害史》&#xff0c;不免令人心惊肉跳。原来古老的北京曾经遭遇过那么多的灾难和浩劫。洪涝、干旱、蝗灾、瘟疫和地震&#xff0c;几乎所有的自然灾害都光顾过北京&#xff0c;尤其是地震。记得1976年唐山大地震过后&#xff0c;民间曾流传一种说法&#xff0c;说北京…

我喜欢荷兰队,可是今天我爱上了俄罗斯

希丁克 我一直喜欢荷兰队&#xff0c;可是今天早晨我爱上了俄罗斯。我喜欢上了那个像高中生一样羞涩的阿尔沙文、笑面绅士狙击手帕甫柳琴科、长相酷似年轻时屠格涅夫的边锋托尔宾斯基、22岁的天才门将阿金费耶夫以及他们的主帅、足球国际主义者、荷兰人希丁克。刘建宏说荷兰是被…

图片浏览控件。。

代码暂时不上传。看看图片得了、 图片可以进行各种操作

Ubuntu15.04如何添加163源

具体的源地址如何获取参见以下网站&#xff1a; http://wiki.ubuntu.org.cn/源列表#Vivid.2815.04.29.E7.89.88.E6.9C.AC sudo gedit /etc/apt/sources.list 将下列源复制粘贴至最前面&#xff0c;然后保存退出 deb http://mirrors.163.com/ubuntu/ vivid main restricted univ…

使用MATLAB和Vivado读取txt文件

使用MATLAB和Vivado读取txt文件 MATLAB处理十六进制的数据: 将你的16进制数据保存到txt文件中,打开MATLAB选择workspace->importdata,导入txt文件中的数据,这样会得到cell格式数据(假设名字为textdata),调用函数hex2dec即可,a=hex2dec(textdata),a就是你所想要的数…

意大利终于付出了代价

今天凌晨在西班牙与意大利的4分之一淘汰赛中,意大利这个老爷车终于掉链子了。这场比赛可说是进攻战胜了保守&#xff0c;诚实消灭了狡猾。从他们排出的不思进取的阵型&#xff0c;到迪纳塔莱佯装受伤受到全场嘘声开始&#xff0c;意大利就注定了要输掉他们一直以来的运气。 看着…

电影《蒙古王》剧照

电影《蒙古王》&#xff0c;由德国、俄罗斯和哈萨克斯坦合拍&#xff0c;影片讲述了成吉思汗早年的故事&#xff0c;拍摄期间曾在蒙古、哈萨克斯坦和中国境内的新疆地区取景。影片的导演是俄罗斯人谢尔盖波德罗夫&#xff0c;演员则来自12个国家&#xff0c;中国演员孙红雷出演…

蒙特卡罗方法求一个三维积分(论坛帮顶)

在vs2008 sp1下编译 http://topic.csdn.net/u/20120312/13/a979f330-ff73-4e5d-ae92-d463c93de5bf.html?seed498140863&r77861318#r_77861318 #include <iostream> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <mall…

CRC校验

CRC校验 1 基本原理 CRC校验原理实际上就是在一个p位二进制数据序列之后附加一个r位二进制检验码(序列),从而构成一个总长为n=p+r位的二进制序列。附加一个r位二进制序列、附加在数据序列之后的这个检验码与数据序列的内容之间存在着某种特定的关系。如果因干扰等原因使数据…

64位ubuntu kylin 16.04下tiny4412开发环境搭建

以下内容均来自互联网&#xff0c;我只是大自然的搬运工。 ubuntu用的是ubuntukylin-16.04-desktop-amd64.iso 1&#xff0c;ubuntu和windows时间不统一解决办法&#xff1a; vi里一条命令解决所有问题 sudo timedatectl set-local-rtc 1 2&#xff0c;安装vim sudo apt in…

温网告别了两位美女:伊万和莎娃

在刚刚结束的英国温布尔登网球公开赛女子第三轮的比赛中&#xff0c;我国选手郑洁以6比1和6比4&#xff0c;直落两局淘汰了塞尔维亚美女伊万诺维奇&#xff0c;进入16强&#xff0c;暴了本届温网的最大冷门。伊万诺维奇目前在女子网球排名中名列第一&#xff0c;是当今女子网坛…

一个有意思的CStatic和combobox以及Cedit控件结合使用

如图。。源代码下载地址 http://download.csdn.net/detail/hemmingway/4187082 这是编辑字符串。。。 这是用组合框选择字符串。。。。 使用方法是托一个Static Text控件到窗口上&#xff0c;调整好大小&#xff0c;修改ID&#xff0c;取一个CEditStatic 的变量类型 在头文件里…

LVDS收发传输实例

LVDS收发传输实例 功能图如下: 由PLL(时钟生成)产生基准时钟;FPGA内部产生固定的1024字节位单位的有效数据帧以用作同步的pattern数据,通过LVDS发送出去;同时另一侧,FPGA也接收LVDS数据,进行位对齐处理,并且对有效数据进行解串; 位对齐(bit align)处理 一般情况…

64位Ubuntu kylin 16.04安装wine QQ

sudo apt install wine Wine QQ 下载 下载解压双击第三个deb安装

昨天是欧洲男人的,今天却属于亚洲女人

昨天&#xff0c;欧锦赛落下帷幕&#xff0c;西班牙历史性的以不败的战绩赢得了德劳内杯。欧洲4年一度的足球盛会终于告一段落&#xff0c;西班牙小伙子用自己的技术和顽强成了欧洲狂欢节的主角。而今天&#xff0c;在英国温布尔登网球公开赛上&#xff0c;郑洁以2比0战胜了赛会…

郑洁又淘汰了一个美女瓦伊迪索娃

今晚在温网四分之一比赛中&#xff0c;郑洁继续中国神话&#xff0c;淘汰了捷克天才少女瓦伊迪索娃&#xff0c;杀进四强&#xff0c;创造了中国网球在四大公开赛历史上的最佳战绩。如果明天她在半决赛中战胜小威廉姆斯&#xff0c;就将进入温网决赛。 现在看来&#xff0c;昨天…

_VARIANT_T 到 CSTRING 转换

_VARIANT_T 到 CSTRING 转换 数据类型转换函数 CString CZjyDlg::VariantToString(VARIANT var) { CString strValue; _variant_t var_t; _bstr_t bstr_t; time_t cur_time; CTime time_value; COleCurrency var_currency; switch(var.vt) { case VT_EMPTY: case VT_NULL:strV…

IP核应用之计数器

IP核应用之计数器 IP核创建流程 首先建立一个工程,然后再点击IP Catalog,接着在Search中输入counter,然后点击Binary Counter。进入计数器的配置界面。 进来后,配置位宽为4,设置计数到10 然后点击Control,接着添加一个时钟使能Clock Enable.最后点击创建

发球机器轰灭了中国姑娘的奇迹

刚刚在被大雨中断了两次的温网女单半决赛中&#xff0c;小威廉姆斯以2比0战胜了中国的郑洁。这是大块头对小女孩儿的比赛&#xff0c;是蛮牛与人的较力&#xff0c;是大猩猩与儿童的掰腕。在弱小的郑洁面前&#xff0c;小威确实太强悍了&#xff0c;她的大力正反手回球和扣球&a…