Пример #1
0
        public static Bitmap DrawThumbnail(Image originalImage, ThumbnailType tt, int width, int height)
        {
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (tt)
            {
                case ThumbnailType.ScalingByBoth://指定高宽缩放(可能变形)
                    break;
                case ThumbnailType.GeometricScalingByWidth://指定宽,高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailType.GeometricScalingByHeight://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                default://指定高宽裁减(不变形)
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;

            }
            //新建一个bmp图片
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
             new Rectangle(x, y, ow, oh),
             GraphicsUnit.Pixel);

            return bitmap;
        }
Пример #2
0
 public static string Make(string sourcedir,string targetdir, string originalName,int width,int height,ThumbnailType type)
 {
     string thumbnailName = Path.GetFileNameWithoutExtension(originalName) + "_" + width + "-" + height + Path.GetExtension(originalName);
     string thumbnailPath = targetdir +  width + "_" + height + "\\";
     string thumbnailFullName = thumbnailPath + thumbnailName;
     NLibrary.IOHelper.EnsureFileDirectory(thumbnailPath);
     if (!File.Exists(thumbnailFullName))
     {
         MakeThumbnail(sourcedir + originalName, thumbnailFullName, type, width, height);
     }
     return thumbnailFullName;
 }
Пример #3
0
        private static void saveAvatarPrivate( int x, int y, String srcPath, ThumbnailType ttype )
        {
            String thumbPath = Img.GetThumbPath( srcPath, ttype );

            Image img = Image.FromFile( srcPath );
            if (img.Size.Width <= x && img.Size.Height <= y) {
                File.Copy( srcPath, thumbPath );
            }
            else {
                Img.SaveThumbnail( srcPath, thumbPath, x, y, SaveThumbnailMode.Cut );
            }
        }
Пример #4
0
        public ActionResult Thumbnail(string thumbnail, ThumbnailType type)
        {
            var responseHeaders = Response.GetTypedHeaders();
            responseHeaders.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromDays(300)
            };

            var file = _thumbnailCacheService.GetThumbnail(thumbnail, type);

            string contentType = null;
            if (!_contentTypeProvider.TryGetContentType(file, out contentType))
                throw new Exception("Can't get content type for " + file);

            return PhysicalFile(file, contentType);
        }
Пример #5
0
        /// <summary>
        /// 删除图片以及指定类型的缩略图。如果图片不存在,则忽略
        /// </summary>
        /// <param name="srcPath">相对网址</param>
        /// <param name="arrThumbType">多个缩略图类型</param>
        public static void DeleteImgAndThumb( String srcPath, ThumbnailType[] arrThumbType )
        {
            if (strUtil.IsNullOrEmpty( srcPath )) return;
            if (srcPath.ToLower().StartsWith( "http://" )) return;

            String path = PathHelper.Map( srcPath );
            if (file.Exists( path ))
                wojilu.IO.File.Delete( path );

            foreach (ThumbnailType ttype in arrThumbType) {

                String pathThumb = PathHelper.Map( GetThumbPath( srcPath, ttype ) );
                if (file.Exists( pathThumb ))
                    wojilu.IO.File.Delete( pathThumb );
            }
        }
Пример #6
0
        public Thumbnail(byte[] thumbnail,ThumbnailType type)
        {
            thumbType = type;
            Stream stream = new MemoryStream(thumbnail);
            FileReader reader = new FileReader(stream);
            reader.ReadBytes(4);//skip Tag 'THUM'

            width = (int)(reader.ReadUInt32());
            height = (int)(reader.ReadUInt32());

            byte[] readBytes = reader.ReadBytes(thumbnail.Length-12);
            pngBytes = new byte[readBytes.Length];
            readBytes.CopyTo(pngBytes, 0);

            stream.Close();
            reader.Close();
        }
Пример #7
0
        /// <summary>
        /// 根据主题id得到缩略图附件对象
        /// </summary>
        /// <param name="tid">主题id</param>
        /// <param name="maxsize">最大图片尺寸</param>
        /// <param name="type">缩略图类型</param>
        /// <returns>缩略图附件对象</returns>
        public static AttachmentInfo GetThumbnailAttachByTid(int tid, int maxsize, ThumbnailType type)
        {
            int theMaxsize = 300;

            if (maxsize < theMaxsize)
            {
                theMaxsize = maxsize;
            }
            string         attCachePath = string.Format("{0}cache/thumbnail/t_{1}_{2}_{3}.jpg", "/", tid, theMaxsize, (int)type);
            AttachmentInfo attach       = GetFirstImageAttachByTid(tid);

            if (attach == null)
            {
                return(null);
            }
            attach.Attachment = attCachePath;
            string attPhyCachePath = Utils.GetMapPath(attCachePath);

            if (!File.Exists(attPhyCachePath))
            {
                CreateTopicAttThumbnail(attPhyCachePath, type, Utils.GetMapPath(attach.Filename), theMaxsize);
            }
            return(attach);
        }
Пример #8
0
 public ThumbnailViewModel(string id, string title, string imageUrl, string description, string releaseDate, ThumbnailType type)
 {
     this.Id          = id;
     this.Title       = title;
     this.ImageUrl    = imageUrl;
     this.Description = description;
     this.ReleaseDate = releaseDate;
     this.Runtime     = Runtime;
     this.Type        = type;
 }
Пример #9
0
        public static void CreateThumbnail(ThumbnailType thumbnailType, string source, string dest, int thumbWidth, int thumbHeight, Brush backgroundBrush)
        {
            Bitmap sourceImage = new Bitmap(source);
            // Save thumbnail and output it onto the webpage
            int originalWidth = sourceImage.Width;
            int originalHeight = sourceImage.Height;

            int finalWidth = thumbWidth;
            int finalHeight = thumbHeight;

            CalculateRatio(originalWidth, originalHeight, ref thumbWidth, ref thumbHeight);
            int xPos = 0;
            int yPos = 0;

            if (thumbnailType == ThumbnailType.Boxed)
            {
                xPos = (finalWidth - thumbWidth) / 2;
                yPos = (finalHeight - thumbHeight) / 2;
            }
            else
            {
                finalWidth = thumbWidth;
                finalHeight = thumbHeight;
            }

            Bitmap thumbImage = new Bitmap(finalWidth, finalHeight);

            Graphics g = Graphics.FromImage(thumbImage);
            g.FillRectangle(backgroundBrush, new Rectangle(0, 0, finalWidth, finalHeight));
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(sourceImage, xPos, yPos, thumbWidth, thumbHeight);
            thumbImage.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg);
            thumbImage.Dispose();
            sourceImage.Dispose();
        }
Пример #10
0
        private static void MakeThumbnail(string originalImagePath,string thumbnailPath, ThumbnailType tt, int width, int height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            Bitmap bitmap = DrawThumbnail(originalImage, tt, width, height);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                //bitmap. g.Dispose();
            }
        }
Пример #11
0
    /// <summary>
    /// 生成缩略图 (按比例缩小图片)
    /// </summary>
    /// <param name="sourcePath">源图片</param>
    /// <param name="outPath">缩略图</param>
    /// <param name="intWidth">图片宽带</param>
    /// <param name="intHeight">图片高度</param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool GenerateThumbnail(string sourcePath, string outPath, int intWidth, int intHeight, ThumbnailType type)
    {
        if (type == ThumbnailType.Zoom)
        {
            return(GenerateThumbnail1(sourcePath, outPath, intWidth, intHeight));
        }

        if (type == ThumbnailType.NotProportional)
        {
            return(GenerateThumbnail2(sourcePath, outPath, intWidth, intHeight));
        }

        if (type == ThumbnailType.Cut)
        {
            return(GenerateThumbnail3(sourcePath, outPath, intWidth, intHeight));
        }

        return(false);
    }
Пример #12
0
        public bool SaveFile(Stream fileStream, string fileName, bool isPublic, out StorageFile outStorageFile, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = false, object extensionConfig = null)
        {
            Argument.ThrowIfNullOrEmpty(fileName, "文件名");
            outStorageFile = null;
            try
            {
                var fileSize = fileStream.Length;
                if (fileSize > 0)
                {
                    var    fileId = KeyGenerator.GetGuidKey();
                    string relativePath;
                    var    savePath = GetFolderPath(out relativePath);
                    relativePath = relativePath.Replace("\\", "/");
                    var fileExtension = Path.GetExtension(fileName)?.ToLower();

                    var fileType = fileName.GetFileType();
                    int imageWidth = 0, imageHeight = 0;

                    //保存到文件
                    var path = $"{savePath}\\{fileId}{fileExtension}";
                    if (fileType == FileType.Image)
                    {
                        //取长宽
                        System.Drawing.Image tempimage = System.Drawing.Image.FromStream(fileStream, true);
                        imageWidth  = tempimage.Width;  //宽
                        imageHeight = tempimage.Height; //高

                        tempimage.Save(path);
                    }
                    else
                    {
                        fileStream.Position = 0;
                        StreamWriter sw = new StreamWriter(path);
                        fileStream.CopyTo(sw.BaseStream);
                        sw.Flush();
                        sw.Close();
                        fileStream.Dispose();
                    }

                    var storageFile = new StorageFile
                    {
                        Id              = fileId,
                        FileName        = fileName,
                        FileExtension   = fileExtension,
                        FileSize        = fileSize.Kb(),
                        RelativePath    = $"{relativePath}/{fileId}{fileExtension}",
                        CreateTime      = DateTime.Now,
                        FileType        = fileType,
                        Width           = imageWidth,
                        Height          = imageHeight,
                        IsPublic        = isPublic,
                        ExtensionConfig = extensionConfig?.ToJson()
                    };

                    //生成缩略图,添加水印
                    if (fileType == FileType.Image)
                    {
                        WaterMark waterMarkConfig = null;
                        //添加水印
                        if (waterMark)
                        {
                            waterMarkConfig = _configService.Get <SystemConfig>().WaterMark;
                        }

                        mediumThumbnailWidth        = mediumThumbnailWidth ?? MediumThumbnailWidth;
                        mediumThumbnailHeight       = mediumThumbnailHeight ?? MediumThumbnailHeight;
                        storageFile.MediumThumbnail = storageFile.RelativePath.GetThumbnail(mediumThumbnailWidth.Value, mediumThumbnailHeight.Value, thumbnailType, waterMarkConfig);

                        smallThumbnailWidth        = smallThumbnailWidth ?? SmallThumbnailWidth;
                        smallThumbnailHeight       = smallThumbnailHeight ?? SmallThumbnailHeight;
                        storageFile.SmallThumbnail = storageFile.RelativePath.GetThumbnail(smallThumbnailWidth.Value, smallThumbnailHeight.Value, thumbnailType, waterMarkConfig);

                        storageFile.RelativePath.BuildWaterMark(waterMarkConfig);
                    }

                    var success = _currencyService.Create(storageFile);
                    if (success)
                    {
                        outStorageFile = storageFile;
                        Logger.Operation($"添加文件:{fileName}", SystemSettingsModule.Instance);
                    }
                    return(success);
                }
                return(false);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "上传文件出错");
                return(false);
            }
        }
Пример #13
0
        /// <summary>
        /// 保存上传的图片
        /// </summary>
        /// <param name="postedFile"></param>
        /// <param name="arrThumbType"></param>
        /// <returns></returns>
        public static Result SaveImg( HttpFile postedFile, ThumbnailType[] arrThumbType )
        {
            Result result = new Result();

            checkUploadPic( postedFile, result );
            if (result.HasErrors) {
                logger.Info( result.ErrorsText );
                return result;
            }

            String pathName = PathHelper.Map( sys.Path.DiskPhoto );
            String photoName = Img.GetPhotoName( pathName, postedFile.ContentType );
            String filename = Path.Combine( pathName, photoName );

            try {
                postedFile.SaveAs( filename );

                foreach (ThumbnailType ttype in arrThumbType) {
                    saveThumbSmall( filename, ttype );
                }

            }
            catch (Exception exception) {
                logger.Error( lang.get( "exPhotoUploadError" ) + ":" + exception.Message );
                result.Add( lang.get( "exPhotoUploadErrorTip" ) );
                return result;
            }
            result.Info = photoName.Replace( @"\", "/" );
            return result;
        }
Пример #14
0
        public ActionResult SimpleUploadPartial(string controlId, string moduleKey, string sourceType, int?maxFilesize, string acceptedFiles, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, FileType?fileType = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool?waterMark = false, UploadPartialType uploadType = UploadPartialType.Both)
        {
            Argument.ThrowIfNullOrEmpty(controlId, "controlId");
            if (maxFilesize == null || maxFilesize == 0)
            {
                maxFilesize = 4;
            }
            if (string.IsNullOrWhiteSpace(acceptedFiles))
            {
                acceptedFiles = ".bmp,.jpg,.jpeg,.gif,.png";
            }

            ViewBag.ControlId        = controlId;
            ViewBag.IsPublic         = true;
            ViewBag.MaxFiles         = 1;
            ViewBag.MaxFilesize      = maxFilesize;
            ViewBag.AcceptedFiles    = acceptedFiles;
            ViewBag.AutoProcessQueue = true;
            ViewBag.FileType         = fileType;
            ViewBag.WaterMark        = waterMark;
            ViewBag.UploadType       = uploadType;

            ViewBag.MediumThumbnailWidth  = mediumThumbnailWidth;
            ViewBag.MediumThumbnailHeight = mediumThumbnailHeight;
            ViewBag.SmallThumbnailWidth   = smallThumbnailWidth;
            ViewBag.SmallThumbnailHeight  = smallThumbnailHeight;
            ViewBag.ThumbnailType         = thumbnailType;

            return(PartialView("_PartialSimpleUpload"));
        }
Пример #15
0
        public static void MakeThumbnailImage(string bigImage, string smallImage, int imageWidth, int imageHeight, ThumbnailType thumbnailType)
        {
            if (File.Exists(bigImage))
            {
                try
                {
                    DirectoryInfo info = new DirectoryInfo(smallImage.Substring(0, smallImage.LastIndexOf(@"\")) + @"\");
                    if (!info.Exists)
                    {
                        info.Create();
                    }
                }
                catch
                {
                }
                using (Image image = Image.FromFile(bigImage))
                {
                    switch (thumbnailType)
                    {
                    case ThumbnailType.WidthFix:
                        imageHeight = Convert.ToInt32((double)((Convert.ToDouble(image.Height) * Convert.ToDouble(imageWidth)) / Convert.ToDouble(image.Width)));
                        goto Label_01C9;

                    case ThumbnailType.HeightFix:
                        imageWidth = Convert.ToInt32((double)((Convert.ToDouble(image.Width) * Convert.ToDouble(imageHeight)) / Convert.ToDouble(image.Height)));
                        goto Label_01C9;

                    case ThumbnailType.InBox:
                        if ((Convert.ToDouble(image.Width) / ((double)image.Height)) >= (Convert.ToDouble(imageWidth) / ((double)imageHeight)))
                        {
                            imageHeight = Convert.ToInt32((double)((Convert.ToDouble(image.Height) * Convert.ToDouble(imageWidth)) / Convert.ToDouble(image.Width)));
                        }
                        else
                        {
                            imageWidth = Convert.ToInt32((double)((Convert.ToDouble(image.Width) * Convert.ToDouble(imageHeight)) / Convert.ToDouble(image.Height)));
                        }
                        goto Label_01C9;

                    case ThumbnailType.OutBox:
                        if ((Convert.ToDouble(image.Width) / ((double)image.Height)) < (Convert.ToDouble(imageWidth) / ((double)imageHeight)))
                        {
                            break;
                        }
                        imageWidth = Convert.ToInt32((double)((Convert.ToDouble(image.Width) * Convert.ToDouble(imageHeight)) / Convert.ToDouble(image.Height)));
                        goto Label_01C9;

                    default:
                        goto Label_01C9;
                    }
                    imageHeight = Convert.ToInt32((double)((Convert.ToDouble(image.Height) * Convert.ToDouble(imageWidth)) / Convert.ToDouble(image.Width)));
Label_01C9:
                    using (Bitmap bitmap = new Bitmap(imageWidth, imageHeight))
                    {
                        using (Graphics graphics = Graphics.FromImage(bitmap))
                        {
                            graphics.InterpolationMode  = InterpolationMode.High;
                            graphics.SmoothingMode      = SmoothingMode.HighQuality;
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                            graphics.Clear(Color.White);
                            graphics.DrawImage(image, new Rectangle(0, 0, imageWidth, imageHeight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
                            ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
                            ImageCodecInfo   encoder       = null;
                            foreach (ImageCodecInfo info3 in imageEncoders)
                            {
                                if (info3.MimeType == "image/jpeg")
                                {
                                    encoder = info3;
                                }
                            }
                            EncoderParameters encoderParams = new EncoderParameters();
                            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
                            bitmap.Save(smallImage, encoder, encoderParams);
                        }
                        return;
                    }
                }
            }
        }
Пример #16
0
        public ActionResult UploadedBase64Image(string fileName, string data, bool?isPublic, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = false)
        {
            var result = new DataJsonResult();

            if (string.IsNullOrWhiteSpace(fileName))
            {
                result.ErrorMessage = "图片文件名为空";
                return(Json(result));
            }
            if (string.IsNullOrWhiteSpace(data))
            {
                result.ErrorMessage = "图片数据为空";
                return(Json(result));
            }
            if (string.IsNullOrWhiteSpace(Path.GetExtension(fileName)))
            {
                result.ErrorMessage = "文件名称没有包含扩展名";
                return(Json(result));
            }

            StorageFile storageFile;

            if (!_fileService.SaveFile(data, fileName, isPublic ?? true, out storageFile, mediumThumbnailWidth, mediumThumbnailHeight, smallThumbnailWidth, smallThumbnailHeight, thumbnailType, waterMark))
            {
                result.ErrorMessage = "文件名称没有包含扩展名";
                return(Json(result));
            }
            result.Data = storageFile.Simplified();
            return(Json(result));
        }
Пример #17
0
        public ActionResult UploadPartial(string controlId, Guid?sourceId, string moduleKey, string sourceType, bool?isPublic, int?maxFiles, int?maxFilesize, string acceptedFiles, string defaultValue = "", int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, bool?autoProcessQueue = true, bool?editMode = true, FileType?fileType = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool?waterMark = false, UploadPartialType uploadType = UploadPartialType.Both)
        {
            Argument.ThrowIfNullOrEmpty(controlId, "controlId");
            if (maxFiles == null || maxFiles == 0)
            {
                maxFiles = 1;
            }
            if (maxFilesize == null || maxFilesize == 0)
            {
                maxFilesize = 4;
            }
            if (isPublic == null)
            {
                isPublic = true;
            }
            if (string.IsNullOrWhiteSpace(acceptedFiles))
            {
                acceptedFiles = ".bmp,.jpg,.jpeg,.gif,.png";
            }
            if (autoProcessQueue == null)
            {
                autoProcessQueue = true;
            }

            ViewBag.ControlId        = controlId;
            ViewBag.IsPublic         = isPublic;
            ViewBag.MaxFiles         = maxFiles;
            ViewBag.MaxFilesize      = maxFilesize;
            ViewBag.AcceptedFiles    = acceptedFiles;
            ViewBag.AutoProcessQueue = autoProcessQueue;
            ViewBag.DefaultValue     = defaultValue;
            ViewBag.EditMode         = editMode;
            ViewBag.FileType         = fileType;
            ViewBag.WaterMark        = waterMark;
            ViewBag.UploadType       = uploadType;

            ViewBag.MediumThumbnailWidth  = mediumThumbnailWidth;
            ViewBag.MediumThumbnailHeight = mediumThumbnailHeight;
            ViewBag.SmallThumbnailWidth   = smallThumbnailWidth;
            ViewBag.SmallThumbnailHeight  = smallThumbnailHeight;
            ViewBag.ThumbnailType         = thumbnailType;

            if (sourceId != null)
            {
                var currentFiles = _storageFileService.GetFiles(sourceId.Value, moduleKey, sourceType);

                ViewBag.DefaultValue = string.Join(",", currentFiles.Distinct().Select(f => f.Id));
                ViewBag.CurrentFiles = currentFiles;
            }

            return(PartialView("_PartialUpload"));
        }
Пример #18
0
        private static void CreateTopicAttThumbnail(string attPhyCachePath, ThumbnailType type, string attPhyPath, int theMaxsize)
        {
            if (!attPhyPath.StartsWith("http://"))
            {
                attPhyPath = Utils.GetMapPath(attPhyPath);
            }
            if (!attPhyPath.StartsWith("http://") && !File.Exists(attPhyPath))
            {
                return;
            }
            string mapPath = Utils.GetMapPath(BaseConfigs.GetForumPath + "cache/thumbnail/");

            if (!Directory.Exists(mapPath))
            {
                try
                {
                    Utils.CreateDir(mapPath);
                }
                catch
                {
                    throw new Exception("请检查程序目录下cache文件夹的用户权限!");
                }
            }
            FileInfo[] files = new DirectoryInfo(mapPath).GetFiles();
            if (files.Length > 1500)
            {
                Attachments.QuickSort(files, 0, files.Length - 1);
                for (int i = files.Length - 1; i >= 1400; i--)
                {
                    try
                    {
                        files[i].Delete();
                    }
                    catch
                    {
                    }
                }
            }
            try
            {
                switch (type)
                {
                case ThumbnailType.Square:
                    if (attPhyPath.StartsWith("http://"))
                    {
                        Thumbnail.MakeRemoteSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    }
                    else
                    {
                        Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    }
                    break;

                case ThumbnailType.Thumbnail:
                    if (attPhyPath.StartsWith("http://"))
                    {
                        Thumbnail.MakeRemoteThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                    }
                    else
                    {
                        Thumbnail.MakeThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                    }
                    break;

                default:
                    if (attPhyPath.StartsWith("http://"))
                    {
                        Thumbnail.MakeRemoteSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    }
                    else
                    {
                        Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    }
                    break;
                }
            }
            catch
            {
            }
        }
Пример #19
0
 public static string Thumbnail(this IUrlHelper urlHelper, string thumb, ThumbnailType type)
 {
     return(urlHelper.RouteUrl("Thumbnail", new { thumbnail = thumb, type }));
 }
Пример #20
0
        public string GetThumbnail(string thumbnail, ThumbnailType type)
        {
            var possible = Path.Combine(_thumbnailCacheDirectory, type.ToString(), thumbnail);

            if (File.Exists(possible))
            {
                return(possible);
            }

            // TODO: global sync lock?

            using (var imageStream = _postThumbnailService.GetImage(thumbnail))
            {
                switch (type)
                {
                case ThumbnailType.Full:
                    using (var fileStream = File.OpenWrite(possible))
                        imageStream.CopyTo(fileStream);
                    break;

                case ThumbnailType.Post:

                    using (var image = Image.FromStream(imageStream))
                    {
                        var instructions = new Instructions("width=70&height=70&scale=both")
                        {
                            Width  = 70,
                            Height = 70,
                            Scale  = ScaleMode.Both
                        };

                        // we want horizontally long images to have no padding. simply render the images with a max width.
                        // for vertically long images, we want to fill the entire canvas area with no black space on the sides.
                        var ratio = image.Width / (double)image.Height;
                        if (ratio >= 1.5)
                        {
                            // the image is REALLY wide, so, let's just fill, cropping the ends.
                            instructions.Mode = FitMode.Crop;
                        }
                        else if (ratio >= 1)
                        {
                            // the image is wide
                            instructions.Mode = FitMode.Max;
                        }
                        else
                        {
                            // the image is tall
                            instructions.Mode = FitMode.Crop;
                        }

                        ImageBuilder.Current.Build(new ImageJob()
                        {
                            Source       = image,
                            Dest         = possible,
                            Instructions = instructions
                        });
                    }
                    break;

                default:
                    throw new Exception("unknown type");
                }
            }

            return(possible);
        }
Пример #21
0
        private bool picExist( string userPic, ThumbnailType ttype )
        {
            String srcPath = getSrcPath( userPic );
            String thumbPath = Img.GetThumbPath( srcPath, ttype );

            return file.Exists( thumbPath );
        }
Пример #22
0
        public ActionResult SaveUploadedFile(bool?isPublic, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = false)
        {
            if (isPublic == null)
            {
                isPublic = true;
            }

            var result = new DataJsonResult();

            //虽然是循环,其实一次只会提交一个文件
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];
                StorageFile        storageFile;
                result.Success = _fileService.SaveFile(file, isPublic.Value, out storageFile, mediumThumbnailWidth, mediumThumbnailHeight, smallThumbnailWidth, smallThumbnailHeight, thumbnailType, waterMark);
                if (result.Success)
                {
                    result.Data = storageFile;
                    break;
                }
            }

            return(Json(result));
        }
Пример #23
0
 public String GetPhotoThumb( String relativeUrl, ThumbnailType ttype )
 {
     return wojilu.Drawing.Img.GetThumbPath( GetPhotoOriginal( relativeUrl ), ttype );
 }
Пример #24
0
        public ActionResult UploadedFileKindEdit(bool?isPublic, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = true)
        {
            if (isPublic == null)
            {
                isPublic = true;
            }

            var result = new DataJsonResult();


            HttpPostedFileBase file = Request.Files[0];
            StorageFile        storageFile;

            result.Success = _fileService.SaveFile(file, isPublic.Value, out storageFile, mediumThumbnailWidth, mediumThumbnailHeight, smallThumbnailWidth, smallThumbnailHeight, thumbnailType, waterMark);
            if (result.Success)
            {
                return(Json(new { error = 0, url = "/" + storageFile.RelativePath }));
            }
            return(Json(new { error = 1, message = "上传失败" }));
        }
Пример #25
0
 public bool SaveFile(HttpPostedFileBase file, bool isPublic, out StorageFile outStorageFile, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = false, object extensionConfig = null)
 {
     return(SaveFile(file.InputStream, file.FileName, isPublic, out outStorageFile, mediumThumbnailWidth,
                     mediumThumbnailHeight, smallThumbnailWidth, smallThumbnailHeight, thumbnailType, waterMark, extensionConfig));
 }
Пример #26
0
        public string GetThumbnail(string thumbnail, ThumbnailType type)
        {
            var possible = Path.Combine(_thumbnailCacheDirectory, type.ToString(), thumbnail);
            if (File.Exists(possible))
                return possible;

            // TODO: global sync lock?

            using (var imageStream = _postThumbnailService.GetImage(thumbnail))
            {
                switch (type)
                {
                    case ThumbnailType.Full:
                        using (var fileStream = File.OpenWrite(possible))
                            imageStream.CopyTo(fileStream);
                        break;
                    case ThumbnailType.Post:

                        using (var image = Image.FromStream(imageStream))
                        {
                            var instructions = new Instructions("width=70&height=70&scale=both")
                            {
                                Width = 70,
                                Height = 70,
                                Scale = ScaleMode.Both
                            };

                            // we want horizontally long images to have no padding. simply render the images with a max width.
                            // for vertically long images, we want to fill the entire canvas area with no black space on the sides.
                            var ratio = image.Width / (double)image.Height;
                            if (ratio >= 1.5)
                            {
                                // the image is REALLY wide, so, let's just fill, cropping the ends.
                                instructions.Mode = FitMode.Crop;
                            }
                            else if (ratio >= 1)
                            {
                                // the image is wide
                                instructions.Mode = FitMode.Max;
                            }
                            else
                            {
                                // the image is tall
                                instructions.Mode = FitMode.Crop;
                            }

                            ImageBuilder.Current.Build(new ImageJob()
                            {
                                Source = image,
                                Dest = possible,
                                Instructions = instructions
                            });
                        }
                        break;
                    default:
                        throw new Exception("unknown type");
                }
            }

            return possible;
        }
Пример #27
0
        /// <summary>
        /// 绑定附件数组中的参数,返回新上传的附件个数
        /// </summary>
        /// <param name="attachmentInfo">附件类型</param>
        /// <param name="postId">帖子id</param>
        /// <param name="msg">原有提示信息</param>
        /// <param name="topicId">主题id</param>
        /// <param name="userId">用户id</param>
        /// <returns>无效附件个数</returns>
        //public static int BindAttachment(AttachmentInfo[] attachmentInfo, int postId, StringBuilder msg, int topicId, int userId, UserGroupInfo userGroupInfo, out int newAttachmentCount)
        //{
        //    //int acount = attachmentInfo.Length;
        //    // 附件查看权限
        //    string[] readperm = String.IsNullOrEmpty(DNTRequest.GetString("readperm")) ? null : DNTRequest.GetString("readperm").Split(',');
        //    string[] attachdesc = DNTRequest.GetString("attachdesc") == null ? null : DNTRequest.GetString("attachdesc").Split(',');
        //    string[] localid = DNTRequest.GetString("localid") == null ? null : DNTRequest.GetString("localid").Split(',');
        //    string[] attachprice = DNTRequest.GetString("attachprice") == null ? null : DNTRequest.GetString("attachprice").Split(',');
        //    //设置无效附件计数器,将在下面UserCreditsFactory.UpdateUserCreditsByUploadAttachment方法中减去该计数器的值
        //    int errorAttachment = 0;
        //    int i_readperm = 0;
        //    newAttachmentCount = 0;
        //    for (int i = 0; i < attachmentInfo.Length; i++)
        //    {
        //        if (attachmentInfo[i] != null)
        //        {
        //            if (attachmentInfo[i].Pid == 0)
        //                newAttachmentCount++;
        //            attachmentInfo[i].Uid = userId;
        //            attachmentInfo[i].Tid = topicId;
        //            attachmentInfo[i].Pid = postId;
        //            attachmentInfo[i].Postdatetime = Utils.GetDateTime();
        //            attachmentInfo[i].Readperm = 0;
        //            attachmentInfo[i].Attachprice = attachprice != null ? UserGroups.CheckUserGroupMaxPrice(userGroupInfo, Utils.StrToInt(attachprice[i], 0)) : 0;
        //            if (readperm != null)
        //            {
        //                i_readperm = Utils.StrToInt(readperm[i], 0);
        //                //当为最大阅读仅限(255)时
        //                i_readperm = i_readperm > 255 ? 255 : i_readperm;
        //                attachmentInfo[i].Readperm = i_readperm;
        //            }
        //            if (attachdesc != null && !attachdesc[i].Equals(""))
        //                attachmentInfo[i].Description = Utils.HtmlEncode(attachdesc[i]);
        //            //if (!attachmentInfo[i].Sys_noupload.Equals(""))
        //            //{
        //            //    msg.AppendFormat("<tr><td align=\"left\">{0}</td>", attachmentInfo[i].Attachment);
        //            //    msg.AppendFormat("<td align=\"left\">{0}</td></tr>", attachmentInfo[i].Sys_noupload);
        //            //    errorAttachment++;
        //            //}
        //        }
        //    }
        //    //如果有上传错误的,则减去错误的个数
        //    newAttachmentCount -= errorAttachment;
        //    return errorAttachment;
        //}
        /// <summary>
        /// 根据主题id得到缩略图附件对象
        /// </summary>
        /// <param name="tid">主题id</param>
        /// <param name="maxsize">最大图片尺寸</param>
        /// <param name="type">缩略图类型</param>
        /// <returns>缩略图附件对象</returns>
        public static string GetThumbnailByTid(int tid, int maxsize, ThumbnailType type)
        {
            int theMaxsize = maxsize < 300 ? maxsize : 300;
            string attCachePath = string.Format("{0}cache/thumbnail/t_{1}_{2}_{3}.jpg", BaseConfigs.GetForumPath, tid, theMaxsize, (int)type);

            AttachmentInfo attach = Discuz.Data.Attachments.GetFirstImageAttachByTid(tid);
            if (attach == null)
                return null;

            attach.Attachment = attCachePath;
            string attPhyCachePath = Utils.GetMapPath(attCachePath);
            if (!File.Exists(attPhyCachePath))
            {
                CreateTopicAttThumbnail(attPhyCachePath, type, attach.Filename, theMaxsize);
            }
            return attCachePath;
        }
Пример #28
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImage">原图</param>
        /// <param name="thumNailPath">缩略图存储路径</param>
        /// <param name="width">缩略图宽</param>
        /// <param name="height">缩略图高</param>
        /// <param name="model">HW(指定宽高,会变形);W(指定宽度,高度按照比例缩放);H(指定高度,宽度按照等比例缩放);BL(按要缩的宽高比例)</param>
        /// <param name="disposeImg">是否注销图片</param>
        public static void MakeThumNail(System.Drawing.Image originalImage, string thumNailPath, int width, int height, ThumbnailType model, bool disposeImg)
        {
            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

            int thumWidth = width;      //缩略图的宽度
            int thumHeight = height;    //缩略图的高度

            int x = 0;
            int y = 0;

            int originalWidth = originalImage.Width;    //原始图片的宽度
            int originalHeight = originalImage.Height;  //原始图片的高度

            switch (model)
            {
                case ThumbnailType.AssignWidthAndHeight:      //指定高宽缩放,可能变形
                    break;
                case ThumbnailType.AssignWidth:       //指定宽度,高度按照比例缩放
                    thumHeight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailType.AssignHeight:       //指定高度,宽度按照等比例缩放
                    thumWidth = originalImage.Width * height / originalImage.Height;
                    break;
                case ThumbnailType.Cut:
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)thumWidth / (double)thumHeight)
                    {
                        originalHeight = originalImage.Height;
                        originalWidth = originalImage.Height * thumWidth / thumHeight;
                        y = 0;
                        x = (originalImage.Width - originalWidth) / 2;
                    }
                    else
                    {
                        originalWidth = originalImage.Width;
                        originalHeight = originalWidth * height / thumWidth;
                        x = 0;
                        y = (originalImage.Height - originalHeight) / 2;
                    }
                    break;
                case ThumbnailType.AutoMaxPercent:
                    if (originalWidth > width || originalHeight > height)
                    {
                        if (originalWidth >= originalHeight)
                        {
                            thumHeight = originalHeight * width / originalWidth;
                            thumWidth = width;
                        }
                        else
                        {
                            thumWidth = originalWidth * height / originalHeight;
                            thumHeight = height;
                        }
                    }
                    else
                    {
                        thumWidth = originalWidth;
                        thumHeight = originalHeight;
                    }
                    break;
                case ThumbnailType.AutoMinPercent:
                    if (originalWidth > width || originalHeight > height)
                    {
                        var perw = width / (double)originalWidth;
                        var perh = height / (double)originalHeight;
                        var per = Math.Min(perw, perh);
                        thumWidth = (int)Math.Ceiling(originalWidth * per);
                        thumHeight = (int)Math.Ceiling(originalHeight * per);
                    }
                    else
                    {
                        thumWidth = originalWidth;
                        thumHeight = originalHeight;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(thumWidth, thumHeight);

            //新建一个画板
            System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量查值法
            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;
            //设置高质量,低速度呈现平滑程度
            graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            graphic.Clear(System.Drawing.Color.White);

            //在指定位置并且按指定大小绘制原图片的指定部分
            graphic.DrawImage(originalImage, new Rectangle(0, 0, thumWidth, thumHeight), x, y,
                              originalWidth, originalHeight, GraphicsUnit.Pixel, imageAttributes);

            long[] quality = new long[1];
            quality[0] = 100;

            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo jpegICI = null;
            for (int i = 0; i < arrayICI.Length; i++)
            {
                if (arrayICI[i].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[i];//设置JPEG编码
                    break;
                }
            }

            try
            {
                if (jpegICI != null)
                {
                    var dirpath = Path.GetDirectoryName(thumNailPath);
                    if (!Directory.Exists(dirpath))
                        Directory.CreateDirectory(dirpath);

                    bitmap.Save(thumNailPath, jpegICI, encoderParams);
                    //using (FileStream fs = new FileStream(thumNailPath, FileMode.Create))
                    //{
                    //    bitmap.Save(fs, jpegICI, encoderParams);
                    //}
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                if (disposeImg) originalImage.Dispose();
                bitmap.Dispose();
                graphic.Dispose();
            }
        }
Пример #29
0
 public String GetLogoThumb( String relativeUrl, ThumbnailType ttype )
 {
     String original = GetLogoOriginal( relativeUrl );
     return wojilu.Drawing.Img.GetThumbPath( original, ttype );
 }
Пример #30
0
        public static string Make(string sourcedir, string targetdir, string originalName, int width, int height, ThumbnailType type)
        {
            string thumbnailName     = Path.GetFileNameWithoutExtension(originalName) + "_" + width + "-" + height + Path.GetExtension(originalName);
            string thumbnailPath     = targetdir + width + "_" + height + "\\";
            string thumbnailFullName = thumbnailPath + thumbnailName;

            NLibrary.IOHelper.EnsureFileDirectory(thumbnailPath);
            if (!File.Exists(thumbnailFullName))
            {
                MakeThumbnail(sourcedir + originalName, thumbnailFullName, type, width, height);
            }
            return(thumbnailFullName);
        }
        /// <summary>
        /// Publishes the ThumbnailEvent.
        /// </summary>
        /// <param name="bitmap">The bitmap being published.</param>
        /// <param name="thumbnailType">The type of the Thumbnail</param>
        public void SetThumbnail(WriteableBitmap bitmap, ThumbnailType thumbnailType)
        {
            var payload = new ThumbnailEventPayload(bitmap, thumbnailType);

            this.eventAggregator.GetEvent <ThumbnailEvent>().Publish(payload);
        }
Пример #32
0
        private static void MakeThumbnail(string originalImagePath, string thumbnailPath, ThumbnailType tt, int width, int height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (tt)
            {
            case ThumbnailType.ScalingByBoth:    //指定高宽缩放(可能变形)
                break;

            case ThumbnailType.GeometricScalingByWidth:    //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case ThumbnailType.GeometricScalingByHeight:    //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            default:    //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Пример #33
0
        public String GetGroupLogoThumb(String relativeUrl, ThumbnailType ttype)
        {
            String originalGroup = GetGroupLogoOriginal(relativeUrl);

            return(wojilu.Drawing.Img.GetThumbPath(originalGroup, ttype));
        }
Пример #34
0
        /// <summary>
        /// 根据原始图片名称和缩略图类型,获取缩略图名称
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="ttype"></param>
        /// <returns></returns>
        public static String GetThumbPath( Object srcPath, ThumbnailType ttype )
        {
            if (srcPath == null) return "";
            String path = srcPath.ToString();
            if (strUtil.IsNullOrEmpty( path )) return "";

            String ext = Path.GetExtension( path );
            String pathWithoutExt = strUtil.TrimEnd( path, ext );

            if (pathWithoutExt.EndsWith( "_s" )) pathWithoutExt = strUtil.TrimEnd( pathWithoutExt, "_s" );
            if (pathWithoutExt.EndsWith( "_b" )) pathWithoutExt = strUtil.TrimEnd( pathWithoutExt, "_b" );
            if (pathWithoutExt.EndsWith( "_m" )) pathWithoutExt = strUtil.TrimEnd( pathWithoutExt, "_m" );

            String suffix = "_s";
            if (ttype == ThumbnailType.Medium)
                suffix = "_m";
            else if (ttype == ThumbnailType.Big)
                suffix = "_b";

            return pathWithoutExt + suffix + ext;
        }
Пример #35
0
 public static void CreateThumbnail(ThumbnailType thumbnailType, string source, string dest, int thumbWidth, int thumbHeight)
 {
     CreateThumbnail(thumbnailType, source, dest, thumbWidth, thumbHeight, Brushes.White);
 }
Пример #36
0
        /// <summary>
        ///     创建缩略图(缩略图存在时、原图片不存在时,不生成)
        /// </summary>
        /// <param name="oldImagePath">原始图片</param>
        /// <param name="newImagePath">新图片</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="level">图片质量: 1 - 100</param>
        /// <param name="mode">图片尺寸类型 </param>
        public static byte[] MakeThumbnail(string oldImagePath, string newImagePath, int width, int height, ThumbnailType mode, int level)
        {
            newImagePath = newImagePath.Replace("\\", "/");

            // 判断原图片是否存在
            if (!File.Exists(oldImagePath)) { return null; }
            // 判断缩略图存在时,则直接返回
            if (File.Exists(newImagePath)) { return File.ReadAllBytes(newImagePath); }
            // 创建文件夹 
            Directory.CreateDirectory(newImagePath.Substring(0, newImagePath.LastIndexOf("/")));

            using (var oldImage = Image.FromFile(oldImagePath))
            {
                var toWidth = width = oldImage.Width >= width ? width : oldImage.Width;
                var toHeight = height = oldImage.Height >= height ? height : oldImage.Height;

                #region 计算宽高

                switch (mode)
                {
                    case ThumbnailType.W:
                        toHeight = oldImage.Height * width / oldImage.Width;
                        break;
                    case ThumbnailType.H:
                        toWidth = oldImage.Width * height / oldImage.Height;
                        break;
                    case ThumbnailType.Min:
                        toHeight = oldImage.Height * width / oldImage.Width;
                        if (toHeight > height)
                        {
                            toWidth = oldImage.Width * height / oldImage.Height;
                            toHeight = height;
                        }
                        break;
                    case ThumbnailType.Max: //宽度高度取最大值
                        toHeight = oldImage.Height * width / oldImage.Width;
                        if (toHeight < height)
                        {
                            toWidth = oldImage.Width * height / oldImage.Height;
                            toHeight = height;
                        }
                        break;
                }
                // 如果尺寸没变,则做复制操作
                if (toWidth == oldImage.Width && toHeight == oldImage.Height)
                {
                    File.Copy(oldImagePath, newImagePath, true);
                    return File.ReadAllBytes(newImagePath);
                }

                #endregion

                using (var bm = new Bitmap(toWidth, toHeight))
                {
                    using (var g = Graphics.FromImage(bm))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode = InterpolationMode.High;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.Clear(Color.White);
                        g.DrawImage(oldImage, new Rectangle(0, 0, toWidth, toHeight), new Rectangle(0, 0, oldImage.Width, oldImage.Height), GraphicsUnit.Pixel);
                        g.Dispose();
                    }
                    SetQuality(level);
                    bm.Save(newImagePath, Ici, Ep);
                    bm.Dispose();
                }
                oldImage.Dispose();
            }
            if (mode == ThumbnailType.Cut) { Cut(newImagePath, 0, 0, width, height); }

            return File.ReadAllBytes(newImagePath);
        }
 public void PickThumbnail(MediaData mediaData, ThumbnailType thumbnailType)
 {
     this.PickThumbnailCalled = true;
 }
Пример #38
0
        public static Boolean saveAvatarPrivate( int x, int y, String srcPath, ThumbnailType ttype )
        {
            String thumbPath = Img.GetThumbPath( srcPath, ttype );

            try {
                using (Image img = Image.FromFile( srcPath )) {
                    if (img.Size.Width <= x && img.Size.Height <= y) {
                        File.Copy( srcPath, thumbPath );
                    }
                    else if (img.RawFormat.Equals( System.Drawing.Imaging.ImageFormat.Gif ) && ImageAnimator.CanAnimate( img )) {
                        File.Copy( srcPath, thumbPath );
                    }
                    else {
                        logger.Info( "save thumbnail..." + ttype.ToString() + ": " + srcPath + "=>" + thumbPath );
                        Img.SaveThumbnail( srcPath, thumbPath, x, y, SaveThumbnailMode.Cut );
                    }
                    return true;
                }

            }
            catch (OutOfMemoryException ex) {
                logger.Error( "file format error: " + srcPath );
                return false;
            }
        }
Пример #39
0
 public String GetAvatarThumb( String relativeUrl, ThumbnailType ttype )
 {
     String originalAvatar = GetAvatarOriginal( relativeUrl );
     return wojilu.Drawing.Img.GetThumbPath( originalAvatar, ttype );
 }
Пример #40
0
		/// <summary>
		/// 根据主题id得到缩略图地址
		/// </summary>
		/// <param name="tid">主题id</param>
		/// <param name="maxsize">最大图片尺寸</param>
		/// <param name="type">缩略图类型</param>
		/// <returns>缩略图地址</returns>
		public static string GetThumbnailByTid(int tid, int maxsize, ThumbnailType type)
		{
			int theMaxsize = 300;
			if (maxsize < theMaxsize)
			{
				theMaxsize = maxsize;
			}
			string attCachePath = string.Format("{0}cache/thumbnail/t_{1}_{2}_{3}.jpg", "/", tid, theMaxsize, (int)type);
			string attPhyCachePath = Utils.GetMapPath(attCachePath);
			if (!File.Exists(attPhyCachePath))
			{			
				AttachmentInfo attach = GetFirstImageAttachByTid(tid);
				if (attach == null)
					return "";
				attach.Attachment = attCachePath;

				CreateTopicAttThumbnail(attPhyCachePath, type, Utils.GetMapPath(attach.Filename), theMaxsize);
			}
			return attCachePath;
		}
Пример #41
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 /// <param name="thumbnailKey">リビルド対象のサムネイルキー</param>
 /// <param name="imageSource"></param>
 public ThumbnailEncodingInvoker(string thumbnailKey, ImageSource imageSource, ThumbnailType thumbnailType)
 {
     this._ImageSource    = imageSource;
     _rebuildThumbnailKey = thumbnailKey;
     _ThumbnailType       = thumbnailType;
 }
Пример #42
0
	    /// <summary>
	    /// 创建主题附件缩略图
	    /// </summary>
	    /// <param name="attPhyCachePath">缓存文件路径</param>
	    /// <param name="type">缩略图类型</param>
	    /// <param name="attPhyPath">附件物理路径</param>
	    /// <param name="theMaxsize">最大尺寸</param>
		private static void CreateTopicAttThumbnail(string attPhyCachePath, ThumbnailType type, string attPhyPath, int theMaxsize)
		{
			if (!File.Exists(attPhyPath))
				return;
			string cachedir = AppDomain.CurrentDomain.BaseDirectory + "cache/thumbnail/";
			if (!Directory.Exists(cachedir))
			{
			    try
			    {
				    Utils.CreateDir(cachedir);
				}
				catch
				{
				    throw new Exception("请检查程序目录下cache文件夹的用户权限!");
				}
			}
			DirectoryInfo dir = new DirectoryInfo(cachedir);
			FileInfo[] files = dir.GetFiles();

			if (files.Length > 1500)
			{	
				QuickSort(files, 0, files.Length - 1);

				for (int i = files.Length-1; i >= 1400; i--)
				{
					try
					{
						files[i].Delete();
					}
					catch
					{}
				}
			}
            try
            {
                switch (type)
                {
                    case ThumbnailType.Square:
                        Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        break;
                    case ThumbnailType.Thumbnail:
                        Thumbnail.MakeThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                        break;
                    default:
                        Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        break;
                }

                ////当支持FTP上传附件时
                //if (FTPConfigs.GetConfig().Allowuploadattach)
                //{
                //    FTPs ftps = new FTPs();
                //    ftps.AsyncUpLoadFile(attPhyPath);
                //}
            }
            catch
            {
            }
		}
        /// <summary>
        /// Picks a thumbnail of the current media element.
        /// </summary>
        /// <param name="mediaData">The media data o the current element.</param>
        public void PickThumbnail(MediaData mediaData, ThumbnailType thumbnailType)
        {
            if (mediaData != null)
            {
                IRCESmoothStreamingMediaPlugin mediaElement = mediaData.MediaPlugin as IRCESmoothStreamingMediaPlugin;

                if (mediaElement != null)
                {
                    this.StartThumbnailBuffer();
                    bool     thumbnailSeekCompleted = false;
                    TimeSpan currentPosition        = mediaElement.Position;

                    IRCESmoothStreamingMediaPlugin plugin = new RCESmoothStreamingMediaPlugin();

                    DispatcherTimer thubmnailTimer = new DispatcherTimer {
                        Interval = new TimeSpan(0, 0, 0, 5)
                    };

                    thubmnailTimer.Tick += (sender, e) =>
                    {
                        if (thumbnailSeekCompleted)
                        {
                            thumbnailSeekCompleted = false;
                            thubmnailTimer.Stop();
                            WriteableBitmap writeableBitmap =
                                new WriteableBitmap(plugin.VisualElement, null);

                            // writeableBitmap.Render(mediaElement, null);
                            writeableBitmap.Invalidate();
                            this.Model.SetThumbnail(writeableBitmap, thumbnailType);
                            this.PlayerContainerGrid.Children.Remove(plugin.VisualElement);
                            plugin.Unload();
                            plugin         = null;
                            thubmnailTimer = null;
                            this.EndThumbnailBuffer();
                        }
                    };

                    thubmnailTimer.Start();

                    plugin.ManifestReady += e => plugin.SelectMaxAvailableBitrateTracks("cameraAngle", "camera1");

                    plugin.MediaOpened += e =>
                    {
                        e.Position = currentPosition;
                        e.VisualElement.Visibility = Visibility.Collapsed;
                    };

                    plugin.SeekCompleted += (e, success) => thumbnailSeekCompleted = true;
                    plugin.Load();
                    plugin.AutoPlay             = false;
                    plugin.Volume               = 0;
                    plugin.IsMuted              = true;
                    plugin.VisualElement.Width  = mediaElement.VisualElement.ActualWidth;
                    plugin.VisualElement.Height = mediaElement.VisualElement.ActualHeight;
                    this.PlayerContainerGrid.Children.Add(plugin.VisualElement);

                    plugin.AdaptiveSource = mediaElement.AdaptiveSource;
                }
            }
        }
Пример #44
0
        protected static Bitmap MakeThumbnail(Bitmap source, int width, int height, ThumbnailType mode)
        {
            Bitmap originalImage = source;

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case ThumbnailType.HW://指定高宽缩放(可能变形)
                    break;
                case ThumbnailType.W://指定宽,高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailType.H://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case ThumbnailType.CUT://指定高宽裁减(不变形)
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片
            Bitmap bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            originalImage.Dispose();
            g.Dispose();

            return bitmap;
        }
Пример #45
0
        public bool SaveFile(string base64String, string fileName, bool isPublic, out StorageFile outStorageFile, int?mediumThumbnailWidth = null, int?mediumThumbnailHeight = null, int?smallThumbnailWidth = null, int?smallThumbnailHeight = null, ThumbnailType thumbnailType = ThumbnailType.WhiteEdge, bool waterMark = false, object extensionConfig = null)
        {
            string[] imageArrty    = base64String.Split(',');
            string   imgBase64Data = imageArrty[1];
            string   base64        = imgBase64Data;

            byte[] bytes      = Convert.FromBase64String(base64);
            var    fileStream = new MemoryStream(bytes);

            return(SaveFile(fileStream, fileName, isPublic, out outStorageFile, mediumThumbnailWidth,
                            mediumThumbnailHeight, smallThumbnailWidth, smallThumbnailHeight, thumbnailType, waterMark, extensionConfig));
        }
Пример #46
0
 public String GetPhotoThumb(String relativeUrl, ThumbnailType ttype)
 {
     return(wojilu.Drawing.Img.GetThumbPath(GetPhotoOriginal(relativeUrl), ttype));
 }
Пример #47
0
 private static void saveThumbImagePrivate( String filename, ThumbnailType ttype, int x, int y, SaveThumbnailMode sm )
 {
     using (Image img = Image.FromFile( filename )) {
         if (img.Size.Width <= x && img.Size.Height <= y) {
             File.Copy( filename, Img.GetThumbPath( filename, ttype ) );
         }
         else {
             Img.SaveThumbnail( filename, Img.GetThumbPath( filename, ttype ), x, y, sm );
         }
     }
 }
Пример #48
0
        private static void MakeThumbnail(string originalImagePath,string thumbnailPath, ThumbnailType tt, int width, int height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (tt)
            {
                case ThumbnailType.ScalingByBoth://指定高宽缩放(可能变形)
                    break;
                case ThumbnailType.GeometricScalingByWidth://指定宽,高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailType.GeometricScalingByHeight://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                default://指定高宽裁减(不变形)
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;

            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
             new Rectangle(x, y, ow, oh),
             GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Пример #49
0
        /// <summary>
        /// 创建主题附件缩略图
        /// </summary>
        /// <param name="attPhyCachePath">缓存文件路径</param>
        /// <param name="type">缩略图类型</param>
        /// <param name="attPhyPath">附件物理路径</param>
        /// <param name="theMaxsize">最大尺寸</param>
        private static void CreateTopicAttThumbnail(string attPhyCachePath, ThumbnailType type, string attPhyPath, int theMaxsize)
        {
            if (!attPhyPath.StartsWith("http://"))
                attPhyPath = Utils.GetMapPath(attPhyPath);
            if (!attPhyPath.StartsWith("http://") && !File.Exists(attPhyPath))
                return;

            string cachedir = Utils.GetMapPath(BaseConfigs.GetForumPath + "cache/thumbnail/");

            if (!Directory.Exists(cachedir))
            {
                try
                {
                    Utils.CreateDir(cachedir);
                }
                catch
                {
                    throw new Exception("请检查程序目录下cache文件夹的用户权限!");
                }
            }

            FileInfo[] files = new DirectoryInfo(cachedir).GetFiles();

            if (files.Length > 1500)
            {
                QuickSort(files, 0, files.Length - 1);

                for (int i = files.Length - 1; i >= 1400; i--)
                {
                    try
                    {
                        files[i].Delete();
                    }
                    catch
                    { }
                }
            }
            try
            {
                switch (type)
                {
                    case ThumbnailType.Square:
                        if (attPhyPath.StartsWith("http://"))
                            Thumbnail.MakeRemoteSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        else
                            Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        break;
                    case ThumbnailType.Thumbnail:
                        if (attPhyPath.StartsWith("http://"))
                            Thumbnail.MakeRemoteThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                        else
                            Thumbnail.MakeThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                        break;
                    default:
                        if (attPhyPath.StartsWith("http://"))
                            Thumbnail.MakeRemoteSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        else
                            Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                        break;
                }
            }
            catch
            { }
        }
Пример #50
0
        public static void MakeThumbnail(string srcImagePath, string thumbnailPath, int width, int height, ThumbnailType mode = ThumbnailType.HW, ImageFormat imageFormat = null)
        {
            if (imageFormat == null)
            {
                imageFormat = ImageFormat.Jpeg;
            }

            using (var bitmap = Image.FromFile(srcImagePath))
            {
                using (var target = MakeThumbnail(bitmap, width, height, mode))
                {
                    target.Save(thumbnailPath, imageFormat);
                }
            }
        }
Пример #51
0
        private static void saveThumbSmall( String filename, ThumbnailType ttype )
        {
            int x = 0;
            int y = 0;
            SaveThumbnailMode sm = SaveThumbnailMode.Auto;

            if (ttype == ThumbnailType.Small) {
                x = config.Instance.Site.PhotoThumbWidth;
                y = config.Instance.Site.PhotoThumbHeight;
                sm = SaveThumbnailMode.Cut;
            }
            else if (ttype == ThumbnailType.Medium) {
                x = config.Instance.Site.PhotoThumbWidthMedium;
                y = config.Instance.Site.PhotoThumbHeightMedium;
            }
            else if (ttype == ThumbnailType.Big) {
                x = config.Instance.Site.PhotoThumbWidthBig;
                y = config.Instance.Site.PhotoThumbHeightBig;
            }

            using (Image img = Image.FromFile( filename )) {
                if (img.Size.Width <= x && img.Size.Height <= y) {
                    File.Copy( filename, Img.GetThumbPath( filename, ttype ) );
                }
                else {
                    Img.SaveThumbnail( filename, Img.GetThumbPath( filename, ttype ), x, y, sm );
                }
            }
        }
Пример #52
0
        /// <summary>
        /// 创建主题附件缩略图
        /// </summary>
        /// <param name="attPhyCachePath">缓存文件路径</param>
        /// <param name="type">缩略图类型</param>
        /// <param name="attPhyPath">附件物理路径</param>
        /// <param name="theMaxsize">最大尺寸</param>
        private static void CreateTopicAttThumbnail(string attPhyCachePath, ThumbnailType type, string attPhyPath, int theMaxsize)
        {
            if (!File.Exists(attPhyPath))
            {
                return;
            }
            string cachedir = AppDomain.CurrentDomain.BaseDirectory + "cache/thumbnail/";

            if (!Directory.Exists(cachedir))
            {
                try
                {
                    Utils.CreateDir(cachedir);
                }
                catch
                {
                    throw new Exception("请检查程序目录下cache文件夹的用户权限!");
                }
            }
            DirectoryInfo dir = new DirectoryInfo(cachedir);

            FileInfo[] files = dir.GetFiles();

            if (files.Length > 1500)
            {
                QuickSort(files, 0, files.Length - 1);

                for (int i = files.Length - 1; i >= 1400; i--)
                {
                    try
                    {
                        files[i].Delete();
                    }
                    catch
                    {}
                }
            }
            try
            {
                switch (type)
                {
                case ThumbnailType.Square:
                    Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    break;

                case ThumbnailType.Thumbnail:
                    Thumbnail.MakeThumbnailImage(attPhyPath, attPhyCachePath, theMaxsize, theMaxsize);
                    break;

                default:
                    Thumbnail.MakeSquareImage(attPhyPath, attPhyCachePath, theMaxsize);
                    break;
                }

                ////当支持FTP上传附件时
                //if (FTPConfigs.GetConfig().Allowuploadattach)
                //{
                //    FTPs ftps = new FTPs();
                //    ftps.AsyncUpLoadFile(attPhyPath);
                //}
            }
            catch
            {
            }
        }
Пример #53
0
        private void AddThumbnailJSON(ref dynamic obj, ThumbnailType thtype, string fileName, string timeStart, string TimeStep, string TimeRange, int width, int height, bool preserveResolutionRotation, bool pixelmode, int quality = -1)
        {
            string extension = Enum.GetName(typeof(ThumbnailType), thtype); // to get Png, Bmp or Jpg

            dynamic thOutputEntry = new JObject();
            thOutputEntry.FileName = fileName;
            dynamic Format = new JObject();

            dynamic thEntry = new JObject();
            if (!string.IsNullOrWhiteSpace(timeStart)) thEntry.Start = timeStart;
            if (timeStart != strBest)
            {
                if (!string.IsNullOrWhiteSpace(TimeStep)) thEntry.Step = TimeStep;
                if (!string.IsNullOrWhiteSpace(TimeRange)) thEntry.Range = TimeRange;
            }

            thEntry.Type = extension + "Image";

            dynamic Layer = new JObject();
            if (quality != -1)
            {
                Layer.Quality = quality;
            }
            Layer.Type = extension + "Layer";

            if (pixelmode)
            {
                Layer.Width = width;
                Layer.Height = height;
            }
            else // percentage
            {
                Layer.Width = width.ToString() + "%";
                Layer.Height = height.ToString() + "%";

                if (preserveResolutionRotation)
                {
                    thEntry.PreserveResolutionAfterRotation = true;
                }
            }

            switch (thtype)
            {
                case ThumbnailType.Bmp:
                    thEntry.BmpLayers = new JArray() as dynamic;
                    thEntry.BmpLayers.Add(Layer);
                    break;

                case ThumbnailType.Png:
                    thEntry.PngLayers = new JArray() as dynamic;
                    thEntry.PngLayers.Add(Layer);
                    break;

                case ThumbnailType.Jpg:
                    thEntry.JpgLayers = new JArray() as dynamic;
                    thEntry.JpgLayers.Add(Layer);
                    break;
            }

            obj.Codecs.Add(thEntry);

            Format.Type = extension + "Format";
            thOutputEntry.Format = Format;
            obj.Outputs.Add(thOutputEntry);
        }
Пример #54
0
        private static Boolean saveThumbSmall( String filename, ThumbnailType ttype )
        {
            int x = 0;
            int y = 0;
            SaveThumbnailMode sm = SaveThumbnailMode.Auto;

            if (ttype == ThumbnailType.Small) {
                x = config.Instance.Site.PhotoThumbWidth;
                y = config.Instance.Site.PhotoThumbHeight;
                sm = SaveThumbnailMode.Cut;
            }
            else if (ttype == ThumbnailType.Medium) {
                x = config.Instance.Site.PhotoThumbWidthMedium;
                y = config.Instance.Site.PhotoThumbHeightMedium;
            }
            else if (ttype == ThumbnailType.Big) {
                x = config.Instance.Site.PhotoThumbWidthBig;
                y = config.Instance.Site.PhotoThumbHeightBig;
            }

            try {
                saveThumbImagePrivate( filename, ttype, x, y, sm );
                return true;
            }
            catch (OutOfMemoryException ex) {
                logger.Error( "file format error: " + filename );
                return false;
            }
        }
 public void SetThumbnail(WriteableBitmap bitmap, ThumbnailType thumbnailType)
 {
     throw new NotImplementedException();
 }
Пример #56
0
        public String GetAvatarThumb(String relativeUrl, ThumbnailType ttype)
        {
            String originalAvatar = GetAvatarOriginal(relativeUrl);

            return(wojilu.Drawing.Img.GetThumbPath(originalAvatar, ttype));
        }
Пример #57
0
        /// <summary>
        ///     创建缩略图(缩略图存在时、原图片不存在时,不生成)
        /// </summary>
        /// <param name="oldImagePath">原始图片</param>
        /// <param name="newImagePath">新图片</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="level">图片质量: 1 - 100</param>
        /// <param name="mode">图片尺寸类型 </param>
        public static byte[] MakeThumbnail(string oldImagePath, string newImagePath, int width, int height, ThumbnailType mode, int level)
        {
            newImagePath = newImagePath.Replace("\\", "/");

            // 判断原图片是否存在
            if (!File.Exists(oldImagePath))
            {
                return(null);
            }
            // 判断缩略图存在时,则直接返回
            if (File.Exists(newImagePath))
            {
                return(File.ReadAllBytes(newImagePath));
            }
            // 创建文件夹
            Directory.CreateDirectory(newImagePath.Substring(0, newImagePath.LastIndexOf("/")));

            using (var oldImage = Image.FromFile(oldImagePath))
            {
                var toWidth  = width = oldImage.Width >= width ? width : oldImage.Width;
                var toHeight = height = oldImage.Height >= height ? height : oldImage.Height;

                #region 计算宽高
                switch (mode)
                {
                case ThumbnailType.W: toHeight = oldImage.Height * width / oldImage.Width; break;

                case ThumbnailType.H: toWidth = oldImage.Width * height / oldImage.Height; break;

                case ThumbnailType.Min: toHeight = oldImage.Height * width / oldImage.Width;
                    if (toHeight > height)
                    {
                        toWidth  = oldImage.Width * height / oldImage.Height;
                        toHeight = height;
                    }
                    break;

                case ThumbnailType.Max:     //宽度高度取最大值
                    toHeight = oldImage.Height * width / oldImage.Width;
                    if (toHeight < height)
                    {
                        toWidth  = oldImage.Width * height / oldImage.Height;
                        toHeight = height;
                    }
                    break;
                }
                // 如果尺寸没变,则做复制操作
                if (toWidth == oldImage.Width && toHeight == oldImage.Height)
                {
                    File.Copy(oldImagePath, newImagePath, true);
                    return(File.ReadAllBytes(newImagePath));
                }
                #endregion

                using (var bm = new Bitmap(toWidth, toHeight))
                {
                    using (var g = Graphics.FromImage(bm))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode  = InterpolationMode.High;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.Clear(Color.White);
                        g.DrawImage(oldImage, new Rectangle(0, 0, toWidth, toHeight), new Rectangle(0, 0, oldImage.Width, oldImage.Height), GraphicsUnit.Pixel);
                        g.Dispose();
                    }
                    setQuality(level);
                    bm.Save(newImagePath, ici, ep);
                    bm.Dispose();
                }
                oldImage.Dispose();
            }
            if (mode == ThumbnailType.Cut)
            {
                Cut(newImagePath, 0, 0, width, height);
            }

            return(File.ReadAllBytes(newImagePath));
        }
Пример #58
0
    /// <summary>
    /// 生成缩略图并压缩图片 (按比例缩小图片)
    /// </summary>
    /// <param name="sourcePath">源图片</param>
    /// <param name="outPath">输出图片</param>
    /// <param name="intWidth">图片宽带</param>
    /// <param name="intHeight">图片高度</param>
    /// <param name="quality">图片质量1-100</param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool GenerateThumbnailAndCompression(string sourcePath, string outPath, int intWidth, int intHeight, int quality, ThumbnailType type)
    {
        if (string.IsNullOrWhiteSpace(sourcePath) || string.IsNullOrWhiteSpace(outPath))
        {
            return(false);
        }

        var tempPath = $"{AppDomain.CurrentDomain.BaseDirectory}Files/Temp/{Guid.NewGuid()}";

        tempPath.CreateDirByFilePath();

        //缩略图片
        var isExists = GenerateThumbnail(sourcePath, tempPath, intWidth, intHeight, type);

        //压缩图片
        var b = CompressionImage(isExists ? tempPath : sourcePath, outPath, quality);

        if (isExists)
        {
            File.Delete(tempPath);
        }

        return(b);
    }
Пример #59
0
        public static Image MakeThumbnail(this Image srcImage, int width, int height, ThumbnailType mode)
        {
            //System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

            int x = 0;
            int y = 0;

            int ow = srcImage.Width;
            int oh = srcImage.Height;

            if (srcImage.Width == width && srcImage.Height == height)
            {
                return(srcImage);
            }

            switch (mode)
            {
            case ThumbnailType.HW:
            {
                if (srcImage.Width > width || srcImage.Height > height)
                {
                    // scale down the smaller dimension
                    if (width * srcImage.Height < height * srcImage.Width)
                    {
                        towidth  = width;
                        toheight = (int)Math.Round((decimal)srcImage.Height * width / srcImage.Width);
                    }
                    else
                    {
                        toheight = height;
                        towidth  = (int)Math.Round((decimal)srcImage.Width * height / srcImage.Height);
                    }
                }
                else
                {
                    towidth  = srcImage.Width;
                    toheight = srcImage.Height;
                }

                x = (int)Math.Round((width - towidth) / 2.0);
                y = (int)Math.Round((height - toheight) / 2.0);
            }
            break;

            case ThumbnailType.W:
                toheight = srcImage.Height * width / srcImage.Width;
                break;

            case ThumbnailType.H:
                towidth = srcImage.Width * height / srcImage.Height;
                break;

            case ThumbnailType.Cut:
                if ((double)srcImage.Width / (double)srcImage.Height > (double)towidth / (double)toheight)
                {
                    oh = srcImage.Height;
                    ow = srcImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (srcImage.Width - ow) / 2;
                }
                else
                {
                    ow = srcImage.Width;
                    oh = srcImage.Width * height / towidth;
                    x  = 0;
                    y  = (srcImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            Image bitmap = new Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(srcImage, new Rectangle(0, 0, towidth, toheight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);

            try
            {
                return(bitmap);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                srcImage.Dispose();
                g.Dispose();
            }
        }
Пример #60
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式(w:指定宽,高度自适应;h:指定高度,宽度自适应;cut:裁剪,图片中心向外;默认w)</param>   
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumbnailType mode)
        {
            try
            {
                using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath))
                {

                    if (mode != ThumbnailType.Cut)
                    {
                        double d1 = double.Parse(width.ToString()) / double.Parse(height.ToString());

                        //宽高比
                        double wd = double.Parse(originalImage.Width.ToString()) / double.Parse(originalImage.Height.ToString());
                        //高宽比
                        double hd = double.Parse(originalImage.Height.ToString()) / double.Parse(originalImage.Width.ToString());


                        double itsw = 0d;
                        double itsh = 0d;
                        int itsin = 0;

                        //与宽高比对比
                        if (d1 > wd)
                        {
                            itsw = d1 - wd;
                        }
                        else
                        {
                            itsw = wd - d1;
                        }

                        //与高宽比对比
                        if (d1 > hd)
                        {
                            itsh = d1 - hd;
                        }
                        else
                        {
                            itsh = hd - d1;
                        }

                        //如果高宽比更接近比例
                        if (itsw > itsh)
                        {
                            mode = ThumbnailType.W;
                        }
                        else
                        {
                            mode = ThumbnailType.H;
                        }
                    }


                    int towidth = width;
                    int toheight = height;

                    int x = 0;
                    int y = 0;
                    int ow = originalImage.Width;
                    int oh = originalImage.Height;

                    switch (mode)
                    {
                        case ThumbnailType.HW://指定高宽缩放(可能变形) 
                            break;
                        case ThumbnailType.W://指定宽,高按比例
                            toheight = originalImage.Height * width / originalImage.Width;
                            break;
                        case ThumbnailType.H://指定高,宽按比例
                            towidth = originalImage.Width * height / originalImage.Height;
                            break;
                        case ThumbnailType.Cut://指定高宽裁减(不变形)
                            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                            {
                                oh = originalImage.Height;
                                ow = originalImage.Height * towidth / toheight;
                                y = 0;
                                x = (originalImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = originalImage.Width;
                                oh = originalImage.Width * height / towidth;
                                x = 0;
                                y = (originalImage.Height - oh) / 2;
                            }
                            break;
                        default:
                            break;
                    }

                    //新建一个bmp图片
                    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                    //新建一个画板
                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                    //设置高质量插值法
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //设置高质量,低速度呈现平滑程度
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //清空画布并以透明背景色填充
                    g.Clear(System.Drawing.Color.Transparent);

                    //在指定位置并且按指定大小绘制原图片的指定部分
                    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

                    try
                    {
                        //以jpg格式保存缩略图
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    finally
                    {
                        originalImage.Dispose();
                        bitmap.Dispose();
                        g.Dispose();
                    }
                }
            }
            catch
            {

            }
        }