VBA – 在用户窗体上的Loadpicture()上创build一个缩略图
我使用Loadpicture()
在用户窗体上的多个Image
控件中加载图片,以创build一些预览。 (用户可以点击Image
打开全尺寸图片)。
由于用户Userform
上的预览Image
高约1厘米,我想加载图片的缩略图(较小的文件大小版本)以限制内存使用量,同时仍将全尺寸(百万像素)的源图片保存在硬盘上。
有没有办法调整在加载事件导入的图片?
PS:我不想改变图片的可见高度/宽度,因为PictureSizeMode
设置为fmPictureSizeModeZoom
。
有一个黑客的方式来做到这一点 – 基本上:
- 创build一个临时
Worksheet
- 创build一个形状并将图片加载到其中并调整图片大小
- 创build一个临时
Chart
并粘贴重新大小的图片 - 将
Chart
导出到临时文件 - 删除临时
Worksheet
- 将临时文件加载到
UserForm
- 删除临时文件
这是有点可怕,但它的作品。 您可能要考虑在代码运行时使用Application.ScreenUpdating = False
,但是单步执行下面的代码以查看它的工作方式非常有用。
Option Explicit Private Sub UserForm_Initialize() ' size of thumbnail Dim lngSide As Long lngSide = 50 ' input jpg and temp file path Dim strInPath As String Dim strOutPath As String strInPath = Environ("USERPROFILE") & "\Desktop\Capture.JPG" strOutPath = Environ("USERPROFILE") & "\Desktop\temp.JPG" ' add a temp worksheet Dim ws As Worksheet Set ws = ThisWorkbook.Sheets.Add ' load picture to shape and RESIZE Dim shp As Shape Set shp = ws.Shapes.AddPicture(Filename:=strInPath, _ LinkToFile:=msoFalse, _ SaveWithDocument:=msoCTrue, _ Left:=20, _ Top:=20, _ Width:=lngSide, _ Height:=lngSide) ' create a chart Dim cht As Chart Set cht = ws.Shapes.AddChart(xlColumnClustered, _ Width:=lngSide, _ Height:=lngSide).Chart ' copy shape picture to chart and export to temp file shp.Copy cht.Paste cht.Export Filename:=strOutPath, FilterName:="jpg" ' remove temp sheet (including shape and chart) with no alerts Application.DisplayAlerts = False ws.Delete Application.DisplayAlerts = True ' load resized temp picture to image control With Me.Image1 .Height = lngSide .Width = lngSide .Picture = LoadPicture(strOutPath) End With ' delete the temp file Kill strOutPath End Sub