Thumbnail 图片帮助

    public class Thumbnail
    {
        private Image srcImage;
        private string srcFileName;

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="FileName">原始图片路径</param>
        public bool SetImage(string FileName)
        {
            srcFileName = FileName;
            try
            {
                srcImage = Image.FromFile(srcFileName);
            }
            catch
            {
                return false;
            }
            return true;

        }

        /// <summary>
        /// 回调
        /// </summary>
        /// <returns></returns>
        public static bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 生成缩略图,返回缩略图的Image对象
        /// </summary>
        /// <param name="Width">缩略图宽度</param>
        /// <param name="Height">缩略图高度</param>
        /// <returns>缩略图的Image对象</returns>
        public Image GetImage(int Width, int Height)
        {
            Image img;
            Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
            return img;
        }

        /// <summary>
        /// 保存缩略图
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        public void SaveThumbnailImage(int Width, int Height)
        {
            switch (Path.GetExtension(srcFileName).ToLower())
            {
                case ".png":
                    SaveImage(Width, Height, ImageFormat.Png);
                    break;
                case ".gif":
                    SaveImage(Width, Height, ImageFormat.Gif);
                    break;
                default:
                    SaveImage(Width, Height, ImageFormat.Jpeg);
                    break;
            }
        }

        /// <summary>
        /// 生成缩略图并保存
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <param name="imgformat">保存的图像格式</param>
        /// <returns>缩略图的Image对象</returns>
        public void SaveImage(int Width, int Height, ImageFormat imgformat)
        {
            if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height))
            {
                Image img;
                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                srcImage.Dispose();
                img.Save(srcFileName, imgformat);
                img.Dispose();
            }
        }

        #region Helper

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image">Image 对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="ici">指定格式的编解码参数</param>
        private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType)
                    return ici;
            }
            return null;
        }

        /// <summary>
        /// 计算新尺寸
        /// </summary>
        /// <param name="width">原始宽度</param>
        /// <param name="height">原始高度</param>
        /// <param name="maxWidth">最大新宽度</param>
        /// <param name="maxHeight">最大新高度</param>
        /// <returns></returns>
        private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
        {
            decimal MAX_WIDTH = (decimal)maxWidth;
            decimal MAX_HEIGHT = (decimal)maxHeight;
            decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;

            int newWidth, newHeight;
            decimal originalWidth = (decimal)width;
            decimal originalHeight = (decimal)height;

            if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
            {
                decimal factor;
                // determine the largest factor
                if (originalWidth / originalHeight > ASPECT_RATIO)
                {
                    factor = originalWidth / MAX_WIDTH;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
                else
                {
                    factor = originalHeight / MAX_HEIGHT;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
            }
            else
            {
                newWidth = width;
                newHeight = height;
            }
            return new Size(newWidth, newHeight);
        }

        /// <summary>
        /// 得到图片格式
        /// </summary>
        /// <param name="name">文件名称</param>
        /// <returns></returns>
        public static ImageFormat GetFormat(string name)
        {
            string ext = name.Substring(name.LastIndexOf(".") + 1);
            switch (ext.ToLower())
            {
                case "jpg":
                case "jpeg":
                    return ImageFormat.Jpeg;
                case "bmp":
                    return ImageFormat.Bmp;
                case "png":
                    return ImageFormat.Png;
                case "gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Jpeg;
            }
        }
        #endregion

        /// <summary>
        /// 制作小正方形
        /// </summary>
        /// <param name="fileName">原图的文件路径</param>
        /// <param name="newFileName">新地址</param>
        /// <param name="newSize">长度或宽度</param>
        public static void MakeSquareImage(string fileName, string newFileName, int newSize)
        {
            Image image = Image.FromFile(fileName);

            int i = 0;
            int width = image.Width;
            int height = image.Height;
            if (width > height)
                i = height;
            else
                i = width;

            Bitmap b = new Bitmap(newSize, newSize);

            try
            {
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;

                //清除整个绘图面并以透明背景色填充
                g.Clear(Color.Transparent);
                if (width < height)
                    g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height - width) / 2, width, width), GraphicsUnit.Pixel);
                else
                    g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width - height) / 2, 0, height, height), GraphicsUnit.Pixel);

                SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(fileName).ToString().ToLower()));
            }
            finally
            {
                image.Dispose();
                b.Dispose();
            }
        }

        /// <summary>
        /// 制作缩略图
        /// </summary>
        /// <param name="fileName">原图路径</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
        {
            Image original = Image.FromFile(fileName);
            Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);
            Image displayImage = new Bitmap(original, _newSize);

            try
            {
                displayImage.Save(newFileName, GetFormat(fileName));
            }
            finally
            {
                original.Dispose();
            }
        }

        /// <summary>
        /// 生成缩略图,返回缩略图的Image对象
        /// </summary>
        /// <param name="rawImage">原始图片</param>
        /// <param name="Width">缩略图宽度</param>
        /// <param name="Height">缩略图高度</param>
        /// <returns>缩略图的Image对象</returns>
        public static Image MakeThumbnailImage(Image rawImage, int Width, int Height)
        {
            if (rawImage.Width == Width && rawImage.Height == Height)
            {
                return rawImage;
            }
            else
            {
                Size _newSize = new Size(Width, Height);
                return new Bitmap(rawImage, _newSize);
            }
        }

        /// <summary>
        /// 将字节数组转换为图片
        /// </summary>
        /// <returns></returns>
        public static Image GetImageByBytes(byte[] bytes)
        {
            Image photo = null;
            if (bytes != null && !bytes.Equals(null))
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    try
                    {
                        photo = Image.FromStream(ms, true);
                    }
                    catch
                    {
                    }
                }
            }
            return photo;
        }

        /// <summary>
        /// 转化图片为Byte数组
        /// </summary>
        /// <param name="pb"></param>
        /// <returns></returns>
        public static byte[] GetBytesByImage(Image pb)
        {
            byte[] photo_byte = null;

            if (pb != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Bitmap bmp = new Bitmap(pb);
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    photo_byte = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
                    bmp.Dispose();
                }
            }

            return photo_byte;
        }
    }

Thumbnail 图片帮助

时间: 2024-11-06 07:49:54

Thumbnail 图片帮助的相关文章

iOS遍历相册中的图片

1 //获取相册的所有图片 2 - (void)reloadImagesFromLibrary 3 { 4 self.images = [[NSMutableArray alloc] init]; 5 dispatch_async(dispatch_get_main_queue(), ^{ 6 7 @autoreleasepool { 8 ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){ 9 NSLog(@

异步下载照片墙

android异步下载照片墙 版权声明:本文出自ShengFQ的博客. 转载请注明出处:http://www.jianshu.com/p/1709ea24ebbb 我的问题 我要实现从服务器端下载一个图片地址列表,并异步下载图片展示在imageview,实现缓存和压缩.如果要下载压缩后的图片,应该是由服务器端先压缩后存储,这里只说客户端范围,不做讨论. 需要预备的知识点: 1.AsyncTask异步调用方法下载json数据 2.listview,viewadapter的高性能写法 3.Handl

ios-获取系统相簿里边的所有照片

#import<AssetsLibrary/AssetsLibrary.h> -(void)getImgs{ dispatch_async(dispatch_get_main_queue(), ^{ NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init]; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){ NSLog(@"相册访问失败 

&lt;Bootstrap&gt; 学习笔记六. 栅格系统使用案例

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="bootstrap/css/bootstrap.css"> <link rel="stylesheet&

使用Python PIL库中的Image.thumbnail函数裁剪图片

今天,是我来到博客园的第五天,发现自己还没有头像,想着上传ubuntu系统中我很喜欢的一个背景图片来当头像,但是因为图片过大,上传失败了.那么,我们如何使用python中强大的PIL库来进行图片裁剪呢? from PIL import Image img = Image.open('avatar.jpg') img.thumbnail((480,480)) img.save('thumb.jpg') 首先,找到自己的图片位置,接着如下: 一.从PIL库中导入Image 二.调用Image.ope

如何在线制作gif图片?

最近想做个gif在线制作的网站,所以研究下了imagemagick和graphicsmagick制作gif图片 站已经做出来了:有兴趣的朋友可以先看看 http://www.sosogif.com/make_online.jsp 源码下载地址1:http://www.quzhuanpan.com/home/sourceList.jsp?type=6 源码下载地址2:http://www.quzhuanpan.com/download/checkResult.action?id=30&type=6

通过tfs-nginx进行图片压缩过程

TFS是一个高可扩展.高可用.高性能.面向互联网服务的分布式文件系统,主要针对海量的非结构化数据,它构筑在普通的Linux机器 集群上,可为外部提供高可靠和高并发的存储访问.TFS为淘宝提供海量小文件存储,通常文件大小不超过1M,满足了淘宝对小文件存储的需求,被广泛地应用 在淘宝各项应用中.它采用了HA架构和平滑扩容,保证了整个文件系统的可用性和扩展性.同时扁平化的数据组织结构,可将文件名映射到文件的物理地址,简化了文件的访问流程,一定程度上为TFS提供了良好的读写性能. NameServer主

获取图片

#import "XMGSeeBigPictureViewController.h" #import <UIImageView+WebCache.h> #import "XMGTopic.h" #import <SVProgressHUD.h> #import <AssetsLibrary/AssetsLibrary.h> @interface XMGSeeBigPictureViewController () <UIScr

plupload上传前预览图片

plupload预览图片有多种方法,主要由moxie的Image提供,Image的downsize.crop.embed都可用来预览图片 1.downsize 最开始做项目的时候,我用的就是downsize来做预览图片 downsize(opts) Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions. Argume