C#选择文件返回缩略图
传入文件路径,返回临时文件中缩略图的路径,jpg,pdf,office,rar都行
string path = ThumbnailHelper.GetInstance().GetJPGThumbnail("D:\\1.jpg");
ThumbnailHelper
public class Win32Helper
{
internal const string IShellItem2Guid = "7E9FB0D3-919F-4307-AB2E-9B1860310C93"; [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string path,
// The following parameter is not used - binding context.
IntPtr pbc,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItem shellItem); [DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject); [ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
internal interface IShellItem
{
void BindToHandler(IntPtr pbc,
[MarshalAs(UnmanagedType.LPStruct)]Guid bhid,
[MarshalAs(UnmanagedType.LPStruct)]Guid riid,
out IntPtr ppv); void GetParent(out IShellItem ppsi);
void GetDisplayName(SIGDN sigdnName, out IntPtr ppszName);
void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
void Compare(IShellItem psi, uint hint, out int piOrder);
};
public enum ThumbnailOptions : uint
{
None = ,
ReturnOnlyIfCached = ,
ResizeThumbnail = ,
UseCurrentScale =
}
internal enum SIGDN : uint
{
NORMALDISPLAY = ,
PARENTRELATIVEPARSING = 0x80018001,
PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
DESKTOPABSOLUTEPARSING = 0x80028000,
PARENTRELATIVEEDITING = 0x80031001,
DESKTOPABSOLUTEEDITING = 0x8004c000,
FILESYSPATH = 0x80058000,
URL = 0x80068000
} internal enum HResult
{
Ok = 0x0000,
False = 0x0001,
InvalidArguments = unchecked((int)0x80070057),
OutOfMemory = unchecked((int)0x8007000E),
NoInterface = unchecked((int)0x80004002),
Fail = unchecked((int)0x80004005),
ElementNotFound = unchecked((int)0x80070490),
TypeElementNotFound = unchecked((int)0x8002802B),
NoObject = unchecked((int)0x800401E5),
Win32ErrorCanceled = ,
Canceled = unchecked((int)0x800704C7),
ResourceInUse = unchecked((int)0x800700AA),
AccessDenied = unchecked((int)0x80030005)
} [ComImportAttribute()]
[GuidAttribute("bcc18b79-ba16-442f-80c4-8a59c30c463b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItemImageFactory
{
[PreserveSig]
HResult GetImage(
[In, MarshalAs(UnmanagedType.Struct)] NativeSize size,
[In] ThumbnailOptions flags,
[Out] out IntPtr phbm);
} [StructLayout(LayoutKind.Sequential)]
internal struct NativeSize
{
private int width;
private int height; public int Width { set { width = value; } }
public int Height { set { height = value; } }
}; [StructLayout(LayoutKind.Sequential)]
public struct RGBQUAD
{
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
public byte rgbReserved;
}
}
public class ThumbnailHelper
{
#region instance
private static object ooo = new object();
private static ThumbnailHelper _ThumbnailHelper;
private ThumbnailHelper() { }
public static ThumbnailHelper GetInstance()
{
if (_ThumbnailHelper == null)
{
lock (ooo)
{
if (_ThumbnailHelper == null)
_ThumbnailHelper = new ThumbnailHelper();
}
}
return _ThumbnailHelper;
}
#endregion #region public methods public string GetJPGThumbnail(string filename, int width = , int height = , Win32Helper.ThumbnailOptions options = Win32Helper.ThumbnailOptions.None)
{
if (!File.Exists(filename))
return string.Empty;
Bitmap bit = GetBitmapThumbnail(filename, width, height, options);
if (bit == null)
return string.Empty;
return GetThumbnailFilePath(bit);
}
#endregion #region private methods
private Bitmap GetBitmapThumbnail(string fileName, int width = , int height = , Win32Helper.ThumbnailOptions options = Win32Helper.ThumbnailOptions.None)
{
IntPtr hBitmap = GetHBitmap(System.IO.Path.GetFullPath(fileName), width, height, options); try
{
Bitmap bmp = Bitmap.FromHbitmap(hBitmap); if (Bitmap.GetPixelFormatSize(bmp.PixelFormat) < )
return bmp; return CreateAlphaBitmap(bmp, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}
finally
{
// delete HBitmap to avoid memory leaks
Win32Helper.DeleteObject(hBitmap);
}
}
private Bitmap CreateAlphaBitmap(Bitmap srcBitmap, System.Drawing.Imaging.PixelFormat targetPixelFormat)
{
Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, targetPixelFormat); System.Drawing.Rectangle bmpBounds = new System.Drawing.Rectangle(, , srcBitmap.Width, srcBitmap.Height); BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat); bool isAlplaBitmap = false; try
{
for (int y = ; y <= srcData.Height - ; y++)
{
for (int x = ; x <= srcData.Width - ; x++)
{
System.Drawing.Color pixelColor = System.Drawing.Color.FromArgb(
Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + ( * x))); if (pixelColor.A > & pixelColor.A < )
{
isAlplaBitmap = true;
} result.SetPixel(x, y, pixelColor);
}
}
}
finally
{
srcBitmap.UnlockBits(srcData);
} if (isAlplaBitmap)
{
return result;
}
else
{
return srcBitmap;
}
} private IntPtr GetHBitmap(string fileName, int width, int height, Win32Helper.ThumbnailOptions options)
{
Win32Helper.IShellItem nativeShellItem;
Guid shellItem2Guid = new Guid(Win32Helper.IShellItem2Guid);
int retCode = Win32Helper.SHCreateItemFromParsingName(fileName, IntPtr.Zero, ref shellItem2Guid, out nativeShellItem); if (retCode != )
throw Marshal.GetExceptionForHR(retCode); Win32Helper.NativeSize nativeSize = new Win32Helper.NativeSize();
nativeSize.Width = width;
nativeSize.Height = height; IntPtr hBitmap;
Win32Helper.HResult hr = ((Win32Helper.IShellItemImageFactory)nativeShellItem).GetImage(nativeSize, options, out hBitmap); Marshal.ReleaseComObject(nativeShellItem); if (hr == Win32Helper.HResult.Ok) return hBitmap; throw Marshal.GetExceptionForHR((int)hr);
} /// <summary>
/// 获取临时文件
/// </summary>
/// <returns></returns>
private FileStream GetTemporaryFilePath(ref string filePath)
{
string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());
var index = path.IndexOf('.');
string temp = path.Substring(, index) + ".li"; var fileStream = File.Create(temp);
filePath = temp;
return fileStream;
}
/// <summary>
/// 参数
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = ; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
const int ExpectHeight = ;
const int ExpectWidth = ;
/// <summary>
/// 得到图片缩放后的大小 图片大小过小不考虑缩放了
/// </summary>
/// <param name="originSize">原始大小</param>
/// <returns>改变后大小</returns>
private System.Drawing.Size ScalePhoto(System.Drawing.Size originSize, bool can)
{
if (originSize.Height * originSize.Width < ExpectHeight * ExpectWidth)
{
can = false;
}
if (can)
{
bool isportrait = false; if (originSize.Width <= originSize.Height)
{
isportrait = true;
} if (isportrait)
{
double ratio = (double)ExpectHeight / (double)originSize.Height;
return new System.Drawing.Size((int)(originSize.Width * ratio), (int)(originSize.Height * ratio));
}
else
{
double ratio = (double)ExpectWidth / (double)originSize.Width;
return new System.Drawing.Size((int)(originSize.Width * ratio), (int)(originSize.Height * ratio));
}
}
else
{
return new System.Drawing.Size(originSize.Width, originSize.Height);
} }
/// <summary>
/// 获取缩略图文件
/// </summary>
/// <param name="BitmapIcon">缩略图</param>
/// <returns>路径</returns>
private string GetThumbnailFilePath(Bitmap bitmap)
{
var filePath = "";
var fileStream = GetTemporaryFilePath(ref filePath); //bitmap.Save(filePath); ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); //image code info 图形图像解码压缩
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);
EncoderParameters encoderParameters = new EncoderParameters { Param = new EncoderParameter[] { myEncoderParameter } };
var sizeScaled = ScalePhoto(bitmap.Size, true);
//去黑色背景
var finalBitmap = ClearBlackBackground(bitmap);
finalBitmap.Save(fileStream, myImageCodecInfo, encoderParameters);
fileStream.Dispose();
return filePath;
} private Bitmap ClearBlackBackground(Bitmap originBitmap)
{
using (var tempBitmap = new Bitmap(originBitmap.Width, originBitmap.Height))
{
tempBitmap.SetResolution(originBitmap.HorizontalResolution, originBitmap.VerticalResolution); using (var g = Graphics.FromImage(tempBitmap))
{
g.Clear(System.Drawing.Color.White);
g.DrawImageUnscaled(originBitmap, , );
}
return new Bitmap(tempBitmap);
}
} #endregion
}
C#选择文件返回缩略图的更多相关文章
- 使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件
使用input:file控件在微信内置浏览器上传文件返回未显示选择的文件 原来的写法: <input type="file" accept="image/x-png ...
- 获取文件的缩略图Thumbnail和通过 AQS - Advanced Query Syntax 搜索本地文件
演示如何获取文件的缩略图 FileSystem/ThumbnailAccess.xaml <Page x:Class="XamlDemo.FileSystem.ThumbnailAcc ...
- android 中获取视频文件的缩略图(非原创)
在android中获取视频文件的缩略图有三种方法: 1.从媒体库中查询 2. android 2.2以后使用ThumbnailUtils类获取 3.调用jni文件,实现MediaMetadataRet ...
- VC中打开对话框选择文件和文件夹
1.选择文件 CFileDialogdlg(true, NULL, NULL, NULL, "所有文件 | *.*", this); ...
- 琐碎--选择文件夹(路径)+生产txt格式的log+数据库操作方式
记录日常工作常用到的一些方法: 1 选择文件操作,并将文件的路径记录下来: OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = f ...
- Java按位置解析文本文件(使用Swing选择文件)
工作中遇到这样的一个需求,按位置解析一些文本文件,它们由头部.详情.尾部组成,并且每一行的长度可能不一样,每一行代表的意思也可能不一样,但是每一行各个位置代表的含义已经确定了. 例如有下面这样一段文本 ...
- Jquery调用从ashx文件返回的jsonp格式的数据处理实例
开发环境:vs2010+jquery-1.4.min.js 解决问题:网上代码比较少,好多调试不通,返回数据不用json而用jsonp主要考虑解决跨域问题 开发步骤:打开VS2010,新建一web站点 ...
- EXCEL VBA 选择文件对话框
Sub XXX() Dim arr() arr = Application.GetOpenFilename("所有支付文件 (*.xls;*.xlsx;*.csv),*.xls;*.xlsx ...
- windows API实现用户选择文件路径的对话框
在编写应用程序时,有时需要用户选择某个文件,以供应用程序使用,比如在某些管理程序中需要打开某一个进程,这个时候需要弹出一个对话框来将文件路径以树形图的形式表示出来,以图形化的方式供用户选择文件路径,而 ...
随机推荐
- php+html5实现无刷新上传,大文件分片上传,断点续传
核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...
- CF452E Three strings 广义后缀自动机
建一个广义后缀自动机统计一下就行,好长时间不敲后缀自动机调了半天~ #include <bits/stdc++.h> using namespace std; namespace IO { ...
- 【gym102394A】Artful Paintings(差分约束系统,二分)
题意:给定一个长为n的序列,每个位置可以选择取或不取,要求构造方案使得: 1.对于前M1个约束,区间[L,R]内取的数量必须严格不少于K 2.对于后M2个约束,区间[L,R]外取的数量必须严格不少于K ...
- 【Leetcode】二进制求和
解题思路: 1. 首先在两个字符串前面补‘0’,使它们等长.否则要一直监督操作是否超出两个字符串的索引. 2. 从后向前遍历所有位数,同位相加.字符相加,利用ASCII码,字符在内部都用数字表示,我们 ...
- (63)通信协议之一json
1.什么是JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于JavaScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使 ...
- [BZOJ4237]稻草人:CDQ分治+单调栈
分析 按\(y\)排序后CDQ分治,可以发现每个点可以影响的是\(x\)坐标的一段区间,可以使用扫描线+单调栈,在单调栈上二分即可解决,时间复杂度\(O(n \log^2 n)\). 通过归并排序可以 ...
- Harmonic Number (II)
Harmonic Number (II) PDF (English) Statistics Forum Time Limit: 3 second(s) Memory Limit: 32 MB I ...
- linux crontab -e生成日期格式
近期公司数据库服务器要上双活项目,实施顾问要收集服务器(磁盘性能数据)IO及VM的一些相关信息,并已日期时间格式生成文件 用crontab –e增加以下内容,它的作用是每隔1个小时启动一次iostat ...
- 关于Tomcat重启和关闭后重启session变化
,当页面第一次访问,session的attribute还未赋值,为null 当页面第二次访问时,这时当前的session的attribute有值了! 到了本文章的点题时刻!! 如果我是直接点击serv ...
- php 防盗链
防盗链的技术已经很普遍了,有些网站不喜欢自己的图片被别的网站直接复制使用,便使用了防盗链的技术,这样别人在直接复制使用网站图片时,图片便会按照程序的设定不显示或显示防盗链等字样. 使用了防盗链技术,不 ...