Пример #1
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="src">原图片文件流</param>
        /// <param name="dest">压缩后图片文件流</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(Stream src, Stream dest, int flag = 90, int size = 1024, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            if (sfsc && src.Length < size * 1024)
            {
                src.CopyTo(dest);
                return(true);
            }

            using (Image iSource = Image.FromStream(src))
            {
                ImageFormat tFormat = iSource.RawFormat;
                int         dHeight = iSource.Height;
                int         dWidth = iSource.Width;
                int         sW, sH;
                //按比例缩放
                Size temSize = new Size(iSource.Width, iSource.Height);
                if (temSize.Width > dHeight || temSize.Width > dWidth)
                {
                    if ((temSize.Width * dHeight) > (temSize.Width * dWidth))
                    {
                        sW = dWidth;
                        sH = (dWidth * temSize.Height) / temSize.Width;
                    }
                    else
                    {
                        sH = dHeight;
                        sW = (temSize.Width * dHeight) / temSize.Height;
                    }
                }
                else
                {
                    sW = temSize.Width;
                    sH = temSize.Height;
                }

                using (Bitmap bmp = new Bitmap(dWidth, dHeight))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.WhiteSmoke);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
                    }

                    //以下代码为保存图片时,设置压缩质量
                    using (EncoderParameters ep = new EncoderParameters())
                    {
                        long[] qy = new long[1];
                        qy[0] = flag;//设置压缩的比例1-100
                        using (EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy))
                        {
                            ep.Param[0] = eParam;
                            try
                            {
                                ImageCodecInfo[] arrayIci    = ImageCodecInfo.GetImageEncoders();
                                ImageCodecInfo   jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG"));
                                if (jpegIcIinfo != null)
                                {
                                    bmp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径
                                    if (dest.Length > 1024 * size)
                                    {
                                        flag = flag - 10;
                                        CompressImage(src, dest, flag, size, false);
                                    }
                                }
                                else
                                {
                                    bmp.Save(dest, tFormat);
                                }
                                return(true);
                            }
                            catch
                            {
                                return(false);
                            }
                        }
                    }
                }
            }
        }
Пример #2
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        /// <param name="isaddwatermark">是否添加水印</param>
        /// <param name="quality">图片品质</param>
        /// <param name="imagePosition">水印位置</param>
        /// <param name="waterImage">水印图片名称</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, bool isaddwatermark, ImagePosition imagePosition, string waterImage = null, int quality = 75)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

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

            switch (mode)
            {
            case "HW":    //指定高宽缩放(可能变形)
                break;

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

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

            case "Cut":    //指定高宽裁减(不变形)
                if (originalImage.Width >= towidth && originalImage.Height >= toheight)
                {
                    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;
                    }
                }
                else
                {
                    x  = (originalImage.Width - towidth) / 2;
                    y  = (originalImage.Height - toheight) / 2;
                    ow = towidth;
                    oh = toheight;
                }
                break;

            case "Fit":    //不超出尺寸,比它小就不截了,不留白,大就缩小到最佳尺寸,主要为手机用
                if (originalImage.Width > towidth && originalImage.Height > toheight)
                {
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    else
                    {
                        towidth = originalImage.Width * height / originalImage.Height;
                    }
                }
                else if (originalImage.Width > towidth)
                {
                    toheight = originalImage.Height * width / originalImage.Width;
                }
                else if (originalImage.Height > toheight)
                {
                    towidth = originalImage.Width * height / originalImage.Height;
                }
                else
                {
                    towidth  = originalImage.Width;
                    toheight = originalImage.Height;
                    ow       = towidth;
                    oh       = toheight;
                }
                break;

            default:
                break;
            }

            //新建一个bmp图片
            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.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

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

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

            //加图片水印
            if (isaddwatermark)
            {
                if (string.IsNullOrEmpty(waterImage))
                {
                    waterImage = "watermarker.png";
                }
                Image copyImage = System.Drawing.Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, waterImage));
                //g.DrawImage(copyImage, new Rectangle(bitmap.Width-copyImage.Width, bitmap.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                int xPosOfWm;
                int yPosOfWm;
                int wmHeight = copyImage.Height;
                int wmWidth  = copyImage.Width;
                int phHeight = toheight;
                int phWidth  = towidth;
                switch (imagePosition)
                {
                case ImagePosition.LeftBottom:
                    xPosOfWm = 70;
                    yPosOfWm = phHeight - wmHeight - 70;
                    break;

                case ImagePosition.LeftTop:
                    xPosOfWm = 70;
                    yPosOfWm = 0 - 70;
                    break;

                case ImagePosition.RightTop:
                    xPosOfWm = phWidth - wmWidth - 70;
                    yPosOfWm = 0 - 70;
                    break;

                case ImagePosition.RigthBottom:
                    xPosOfWm = phWidth - wmWidth - 70;
                    yPosOfWm = phHeight - wmHeight - 70;
                    break;

                default:
                    xPosOfWm = 10;
                    yPosOfWm = 0;
                    break;
                }
                g.DrawImage(copyImage, new Rectangle(xPosOfWm, yPosOfWm, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            }

            // 以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityArray = new long[1];
            qualityArray[0] = quality;
            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityArray);

            encoderParams.Param[0] = encoderParam;
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            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)
                {
                    bitmap.Save(thumbnailPath, jpegICI, encoderParams);
                }
                else
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Пример #3
0
        internal PageImage GetPageImage(Report rpt, Row row)
        {
            string mtype = null;
            Stream strm  = null;

            System.Drawing.Image im = null;
            PageImage            pi = null;

            WorkClass wc = GetWC(rpt);

            if (wc.PgImage != null)
            {                              // have we already generated this one
                                           // reuse most of the work; only position will likely change
                pi      = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH);
                pi.Name = wc.PgImage.Name; // this is name it will be shared under
                return(pi);
            }

            try
            {
                strm = GetImageStream(rpt, row, out mtype);
                if (strm == null)
                {
                    rpt.rl.LogError(4, string.Format("Unable to load image {0}.",
                                                     this._Value == null?"": this._Value.EvaluateString(rpt, row)));
                    return(null);
                }
                im = System.Drawing.Image.FromStream(strm);
                int          height = im.Height;
                int          width  = im.Width;
                MemoryStream ostrm  = new MemoryStream();
                ImageFormat  imf;
                //				if (mtype.ToLower() == "image/jpeg")    //TODO: how do we get png to work
                //					imf = ImageFormat.Jpeg;
                //				else

                imf = ImageFormat.Jpeg;
                System.Drawing.Imaging.ImageCodecInfo[] info;
                info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters          = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQualityManager.EmbeddedImageQuality);
                System.Drawing.Imaging.ImageCodecInfo codec = null;
                for (int i = 0; i < info.Length; i++)
                {
                    if (info[i].FormatDescription == "JPEG")
                    {
                        codec = info[i];
                        break;
                    }
                }
                im.Save(ostrm, codec, encoderParameters);

                byte[] ba = ostrm.ToArray();
                ostrm.Close();
                pi    = new PageImage(imf, ba, width, height);
                pi.SI = new StyleInfo();                        // this will just default everything
                if (_BackgroundRepeat != null)
                {
                    string r = _BackgroundRepeat.EvaluateString(rpt, row).ToLower();
                    switch (r)
                    {
                    case "repeat":
                        pi.Repeat = ImageRepeat.Repeat;
                        break;

                    case "repeatx":
                        pi.Repeat = ImageRepeat.RepeatX;
                        break;

                    case "repeaty":
                        pi.Repeat = ImageRepeat.RepeatY;
                        break;

                    case "norepeat":
                    default:
                        pi.Repeat = ImageRepeat.NoRepeat;
                        break;
                    }
                }
                else
                {
                    pi.Repeat = ImageRepeat.Repeat;
                }

                if (_ConstantImage)
                {
                    wc.PgImage = pi;
                    // create unique name; PDF generation uses this to optimize the saving of the image only once
                    pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString();                      // create unique name
                }
            }
            finally
            {
                if (strm != null)
                {
                    strm.Close();
                }
                if (im != null)
                {
                    im.Dispose();
                }
            }
            return(pi);
        }
Пример #4
0
        /// <summary>
        /// Adds the sign text.
        /// </summary>
        /// <param name="img">The img.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="watermarkText">The watermark text.</param>
        /// <param name="watermarkStatus">The watermark status. 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">The quality.</param>
        /// <param name="fontname">The fontname.</param>
        /// <param name="fontsize">The fontsize.</param>
        public static void AddSignText(Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img);
            //    .FromFile(filename);
            Graphics g        = Graphics.FromImage(img);
            Font     drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF    crSize;

            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = img.Width * (float).01;
                ypos = img.Height * (float).01;
                break;

            case 2:
                xpos = (img.Width * (float).50) - (crSize.Width / 2);
                ypos = img.Height * (float).01;
                break;

            case 3:
                xpos = (img.Width * (float).99) - crSize.Width;
                ypos = img.Height * (float).01;
                break;

            case 4:
                xpos = img.Width * (float).01;
                ypos = (img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 5:
                xpos = (img.Width * (float).50) - (crSize.Width / 2);
                ypos = (img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 6:
                xpos = (img.Width * (float).99) - crSize.Width;
                ypos = (img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 7:
                xpos = img.Width * (float).01;
                ypos = (img.Height * (float).99) - crSize.Height;
                break;

            case 8:
                xpos = (img.Width * (float).50) - (crSize.Width / 2);
                ypos = (img.Height * (float).99) - crSize.Height;
                break;

            case 9:
                xpos = (img.Width * (float).99) - crSize.Width;
                ypos = (img.Height * (float).99) - crSize.Height;
                break;

            default:
                break;
            }

            //            System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();
            //            StrFormat.Alignment = System.Drawing.StringAlignment.Center;
            //
            //            g.DrawString(watermarkText, drawFont, new System.Drawing.SolidBrush(System.Drawing.Color.White), xpos + 1, ypos + 1, StrFormat);
            //            g.DrawString(watermarkText, drawFont, new System.Drawing.SolidBrush(System.Drawing.Color.Black), xpos, ypos, StrFormat);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }
            g.Dispose();
            //bmp.Dispose();
            img.Dispose();
        }
Пример #5
0
 private static ImageCodecInfo GetEncoderInfo(String mimeType)
 => ImageCodecInfo.GetImageEncoders().ToList().First(x => x.MimeType == mimeType);
Пример #6
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(WebHelper.GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(WebHelper.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = WebHelper.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = WebHelper.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Пример #7
0
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static byte[] CutForCustom(byte[] fromFile, int maxWidth, int maxHeight, int quality = 100)
        {
            MemoryStream fileSaveStream = new MemoryStream();

            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(new MemoryStream(fromFile), true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原图与模版比例相等,直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原图与模版比例不等,裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
                    Rectangle toR   = new Rectangle(0, 0, 0, 0); //目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X      = 0;
                        fromR.Y      = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width  = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X      = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y      = 0;
                        fromR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //关键质量控制
                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   ici  = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存缩略图
                    templateImage.Save(fileSaveStream, ici, ep);
                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //释放资源
            initImage.Dispose();
            var result = fileSaveStream.ToArray();

            return(result);
        }
Пример #8
0
        /// <summary>
        /// 创建高清缩略图
        /// </summary>
        /// <param name="imgStream">原图路径</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode">尺寸模式</param>
        /// <returns>图片流</returns>
        public static MemoryStream CreateThumbnail(Stream imgStream, int width, int height, ThumbnailMode mode)
        {
            MemoryStream ms = new MemoryStream();

            using (Image source = Image.FromStream(imgStream))
            {
                #region 计算坐标和宽高

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

                switch (mode)
                {
                case ThumbnailMode.Width:
                    height = (int)Math.Round(source.Height * ((double)width / source.Width));
                    break;

                case ThumbnailMode.Height:
                    width = (int)Math.Round(source.Width * ((double)height / source.Height));
                    break;

                case ThumbnailMode.Cut:    //指定高宽裁减(不变形)  yhy
                    if ((double)source.Width / (double)source.Height > (double)width / (double)height)
                    {
                        oh = source.Height;
                        ow = source.Height * width / height;
                        y  = 0;
                        x  = (source.Width - ow) / 2;
                    }
                    else
                    {
                        ow = source.Width;
                        oh = source.Width * height / width;
                        x  = 0;
                        y  = (source.Height - oh) / 2;
                    }
                    break;
                }

                #endregion

                #region 尺寸不变则直接返回

                if (width == ow && height == oh)
                {
                    imgStream.Position = 0;
                    imgStream.CopyTo(ms);
                    return(ms);
                }

                #endregion

                #region 生成缩略图

                using (Bitmap bmp = new Bitmap(width, height))
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(source, new Rectangle(0, 0, width, height), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

                        EncoderParameters parameters = new EncoderParameters();
                        parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[] { 100 });

                        string lookupkey = "image/jpeg";
                        var    codecjpg  = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType.Equals(lookupkey)).FirstOrDefault();

                        bmp.Save(ms, codecjpg, parameters);
                    }

                #endregion
            }
            return(ms);
        }
Пример #9
0
 static ImageUtils()
 {
     JpegCodec = ImageCodecInfo.GetImageEncoders().First(encoder => encoder.MimeType == "image/jpeg");
 }
Пример #10
0
 public static ImageCodecInfo GetCodeInfo(ImgCodes code)
 {
     return(ImageCodecInfo.GetImageEncoders().FirstOrDefault(m => m.MimeType == codes[code]));
 }
Пример #11
0
        public static string CutAvatar(string imgUrl, string newImgUrl, int pointX = 0, int pointY = 0, int width = 0, int height = 0)
        {
            Bitmap   bitmap   = null;
            Image    image    = null;
            Graphics graphics = null;
            Image    image2   = null;

            try
            {
                int thumMaxWidth  = 180;
                int thumMaxHeight = 180;
                if (!string.IsNullOrEmpty(imgUrl))
                {
                    bitmap   = new Bitmap(width, height);
                    image    = Image.FromFile(imgUrl);
                    graphics = Graphics.FromImage(bitmap);
                    graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(pointX, pointY, width, height), GraphicsUnit.Pixel);
                    image2 = GetThumbNailImage(bitmap, thumMaxWidth, thumMaxHeight);
                    EncoderParameters encoderParameters = new EncoderParameters();
                    EncoderParameter  encoderParameter  = new EncoderParameter(value: new long[1]
                    {
                        80L
                    }, encoder: Encoder.Quality);
                    encoderParameters.Param[0] = encoderParameter;
                    ImageCodecInfo[] imageEncoders  = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   imageCodecInfo = null;
                    for (int i = 0; i < imageEncoders.Length; i++)
                    {
                        if (imageEncoders[i].FormatDescription.Equals("JPEG"))
                        {
                            imageCodecInfo = imageEncoders[i];
                            break;
                        }
                    }
                    string text = HttpContext.Current.Server.MapPath(newImgUrl);
                    string path = text.Substring(0, text.LastIndexOf("\\"));
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    if (imageCodecInfo != null)
                    {
                        image2.Save(text, imageCodecInfo, encoderParameters);
                    }
                    else
                    {
                        image2.Save(text);
                    }
                    return(newImgUrl);
                }
                return("");
            }
            catch (Exception)
            {
                return("");
            }
            finally
            {
                bitmap.Dispose();
                image.Dispose();
                graphics.Dispose();
                image2.Dispose();
                GC.Collect();
            }
        }
Пример #12
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="filePath">源图路径(物理路径)</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="mode">
        /// 不区分大小写
        /// case "wh"://指定高宽缩放(可能变形)
        /// case "w"://指定宽,高按比例
        /// case "h"://指定高,宽按比例
        /// case "auto"://等比压缩
        /// case "cut"://指定高宽裁减(不变形)
        /// </param>
        /// <returns>缩略图路径</returns>
        public string DoSmallPic(string filePath, int width, int height, string mode, int sType)
        {
            string imgPath = filePath;

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath);

            int towidth  = width;
            int toheight = height;

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

            if (ow < towidth && oh < toheight)
            {
                return(filePath);
            }

            this.__DoSmallPicCount++;//生成的缩略图数量

            double fwidth              = 0d;
            double fheight             = 0d;
            double proportionForWidth  = (double)width / (double)originalImage.Width;
            double proportionForHeight = (double)height / (double)originalImage.Height;

            mode = mode.ToLower();
            switch (mode)
            {
            case "wh":    //指定高宽缩放(可能变形)
                break;

            case "w":    //指定宽,高按比例
                towidth  = originalImage.Width;
                fheight  = (double)originalImage.Height * proportionForWidth;
                toheight = (int)fheight;
                break;

            case "h":    //指定高,宽按比例
                //towidth = originalImage.Width * height / originalImage.Height;
                fwidth   = (double)originalImage.Width * proportionForHeight;
                towidth  = (int)fwidth;
                toheight = originalImage.Height;
                break;

            case "auto":    //等比压缩
                if (width > originalImage.Width)
                {
                    towidth = originalImage.Width;
                }
                if (height > originalImage.Height)
                {
                    toheight = originalImage.Height;
                }
                if (proportionForWidth > proportionForHeight)
                {
                    fwidth  = proportionForHeight * (double)originalImage.Width;
                    towidth = (int)fwidth;
                }
                else
                {
                    fheight  = proportionForWidth * (double)originalImage.Height;
                    toheight = (int)fheight;
                }
                if (towidth < 1)
                {
                    towidth = 1;
                }
                if (toheight < 1)
                {
                    toheight = 1;
                }
                break;

            case "cut":    //指定高宽裁减(不变形)
                break;

            default:
                break;
            }
            //缩略图路径
            string result = filePath.Substring(0, filePath.LastIndexOf('\\'));

            string[] list = filePath.Split('\\');
            if (list.Length > 0)
            {
                string _fname   = list[list.Length - 1].Trim();
                string ext      = _fname.Substring(_fname.LastIndexOf('.') + 1).ToLower();
                string fileName = _fname.Substring(0, _fname.LastIndexOf('.')).ToLower();

                switch (sType)
                {
                case 0:
                    result += "\\" + fileName + "-" + width + "X" + height + "." + ext;
                    break;

                case 1:
                    result += "\\" + fileName + "_" + width + "_" + height + "." + ext;
                    break;

                default:
                    result += "\\" + fileName + "-" + width + "X" + height + "." + ext;
                    break;
                }
            }
            result = result.Replace(@"\\", @"\");
            //
            //// ===裁剪图片===
            //Bitmap bm = new Bitmap(bitmap);
            //Rectangle cloneRect = new Rectangle(0, 0, towidth, toheight);
            //System.Drawing.Imaging.PixelFormat format = bm.PixelFormat;
            //System.Drawing.Bitmap cloneBitmap = bm.Clone(cloneRect, format);
            //cloneBitmap.Save(Utils.getMapPath(result), System.Drawing.Imaging.ImageFormat.Jpeg);
            //bm.Dispose();
            //try
            //{
            if (mode == "cut")
            {
                //如果是需要裁剪图片
                Bitmap bm = new Bitmap(originalImage);
                try
                {
                    Rectangle cloneRect = new Rectangle(0, 0, towidth, toheight);
                    System.Drawing.Imaging.PixelFormat format = bm.PixelFormat;
                    System.Drawing.Bitmap cloneBitmap         = bm.Clone(cloneRect, format);
                    cloneBitmap.Save(DoRequest.GetMapPath(result), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (Exception) { }
                finally
                {
                    bm.Dispose();
                    originalImage.Dispose();
                }
            }
            else
            {
                //新建一个bmp图片
                System.Drawing.Image    bitmap = new System.Drawing.Bitmap(towidth, toheight);
                System.Drawing.Graphics g      = System.Drawing.Graphics.FromImage(bitmap);

                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                //设置高质量,低速度呈现平滑程度
                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(0, 0, ow, oh),
                            System.Drawing.GraphicsUnit.Pixel);
                // 以下代码为保存图片时,设置压缩质量
                EncoderParameters encoderParams = new EncoderParameters();
                long[]            quality       = new long[1];
                quality[0] = 100;
                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICI  = null;
                for (int xx = 0; xx < arrayICI.Length; xx++)
                {
                    if (arrayICI[xx].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[xx];
                        //设置JPEG编码
                        break;
                    }
                }
                try
                {
                    if (jpegICI != null)
                    {
                        bitmap.Save(result, jpegICI, encoderParams);
                    }
                    else
                    {
                        bitmap.Save(result, originalImage.RawFormat);
                    }
                }
                catch (Exception) { }
                finally
                {
                    bitmap.Dispose();
                    g.Dispose();
                    originalImage.Dispose();
                }
            }

            return(result);
        }
Пример #13
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);

            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return(true);
            }
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat          tFormat = iSource.RawFormat;
            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap   ob = new Bitmap(dWidth, dHeight);
            Graphics g  = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size && size >= 1024)
                    {
                        flag = (int)(1024 * size * 1.0 / fi.Length * 100.0);
                        if (flag < 50)
                        {
                            flag = (int)(flag * 1.5);
                        }
                        //flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                    else if (fi.Length > 1024 * size && size > 500 && size < 1024)
                    {
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
Пример #14
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth">宽度</param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat          tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            int IntWidth;  //新的图片宽
            int IntHeight; //新的图片高

            System.Drawing.Imaging.ImageFormat format = iSource.RawFormat;


            //计算缩放图片的大小

            if (iSource.Width > dWidth && iSource.Height <= dHeight)//宽度比目的图片宽度大,长度比目的图片长度小
            {
                IntWidth  = dWidth;
                IntHeight = (IntWidth * iSource.Height) / iSource.Width;
            }
            else if (iSource.Width <= dWidth && iSource.Height > dHeight)//宽度比目的图片宽度小,长度比目的图片长度大
            {
                IntHeight = dHeight;
                IntWidth  = (IntHeight * iSource.Width) / iSource.Height;
            }
            else if (iSource.Width <= dWidth && iSource.Height <= dHeight) //长宽比目的图片长宽都小
            {
                IntWidth  = iSource.Width;
                IntHeight = iSource.Height;
            }
            else//长宽比目的图片的长宽都大
            {
                IntWidth  = dWidth;
                IntHeight = (IntWidth * iSource.Height) / iSource.Width;
                if (IntHeight > dHeight)//重新计算
                {
                    IntHeight = dHeight;
                    IntWidth  = (IntHeight * iSource.Width) / iSource.Height;
                }
            }
            sW = IntWidth;
            sH = IntHeight;

            System.Drawing.Bitmap SaveImage           = new System.Drawing.Bitmap(sW, sH);
            Graphics g1 = Graphics.FromImage(SaveImage);

            g1.Clear(Color.White);
            Bitmap   ob = new Bitmap(sW, sH);
            Graphics g  = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
Пример #15
0
 public static ImageCodecInfo GetImageCodecInfo(ImageFormat format)
 {
     return(ImageCodecInfo.GetImageEncoders().Where(t => t.FormatID == format.Guid).Single());
 }
Пример #16
0
        /// <summary>
        /// Resmi, MaxWidth x MaxHeight içine sýðabilen hale kadar küçültür.
        /// Bunu yaparken dosya boyutunu da MaxBytes'a sýðdýrmaya çalýþýr.
        /// </summary>
        /// <param name="oStream"></param>
        /// <param name="MaxWidth"></param>
        /// <param name="MaxHeight"></param>
        /// <param name="MaxBytes"></param>
        /// <returns></returns>
        public static System.Drawing.Image ResizeImagesProportional(Stream oStream, int MaxWidth, int MaxHeight, int MaxBytes)
        {
            System.Drawing.Image originalImage = null;

            try
            {
                originalImage = Image.FromStream(oStream);

                // Resmin boyutlarý, izin verilenden zaten küçük ya da eþitse, bir deðiþiklik yapmýyoruz:
                if (originalImage.Width <= MaxWidth && originalImage.Height <= MaxHeight)
                {
                    return(originalImage);
                }
                else
                {
                    // Küçültme oraný
                    decimal proportion         = (MaxWidth / (decimal)originalImage.Width);
                    decimal ProportionalHeight = originalImage.Height * proportion;

                    if (ProportionalHeight > MaxHeight)
                    {
                        MaxWidth = Convert.ToInt32(Convert.ToDecimal(MaxWidth) * Convert.ToDecimal(MaxHeight) / ProportionalHeight);
                    }
                    else
                    {
                        MaxHeight = Convert.ToInt32(ProportionalHeight);
                    }

                    Bitmap       bm            = new Bitmap(originalImage, MaxWidth, MaxHeight);
                    MemoryStream oMemoryStream = new MemoryStream();
                    bm.Save(oMemoryStream, originalImage.RawFormat);

                    if (oMemoryStream.Length > MaxBytes)
                    {
                        oMemoryStream = new MemoryStream();
                        bm.Save(oMemoryStream, ImageFormat.Jpeg);
                    }

                    if (oMemoryStream.Length > MaxBytes)
                    {
                        oMemoryStream = new MemoryStream();
                        bm.Save(oMemoryStream, ImageFormat.Gif);
                    }

                    long Quality = 80L; // %100 kalite
                    // Resmin boyutu izin verilen boyutun altýna düþene kadar %100-90-80... þeklinde küçültüyoruz:
                    while (oMemoryStream.Length > MaxBytes && Quality > 0)
                    {
                        oMemoryStream = new MemoryStream();
                        ImageCodecInfo[]  Info   = ImageCodecInfo.GetImageEncoders();
                        EncoderParameters Params = new EncoderParameters(1);
                        Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality);
                        bm.Save(oMemoryStream, Info[1], Params);
                        Quality -= 10;
                    }
                    originalImage = Image.FromStream(oMemoryStream);
                    bm.Dispose();
                    return(originalImage);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(new Exception("Hatalý resim formatý", ex));
                throw (ex);
            }
        }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler
        /// that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">
        /// An <see cref="T:System.Web.HttpContext"/> object that provides
        /// references to the intrinsic server objects (for example, Request,
        /// Response, Session, and Server) used to service HTTP requests.
        /// </param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // We want aggressive caching since the barcode will not change
                //	for a given set of request parameters however we disable
                //	caching on proxy servers...
                context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);

                // Determine the symbology desired
                string           symbologyText = context.Request.QueryString["sym"];
                BarcodeSymbology symbology;
                if (!TryParseEnum <BarcodeSymbology>(symbologyText, true, out symbology) ||
                    symbology == BarcodeSymbology.Unknown)
                {
                    throw new ArgumentException("Unable to determine symbology.");
                }

                // Get the text to render from the context
                // NOTE: We URL decode it first...
                string textToRender =
                    context.Server.UrlDecode(
                        context.Request.QueryString["text"]);
                if (string.IsNullOrEmpty(textToRender))
                {
                    throw new ArgumentException("Must have text to render as barcode.");
                }

                // Get the rendering metrics from the context
                BarcodeMetrics metrics = GetBarcodeMetricsFromContext(context);

                // Determine the image format (default is jpeg)
                RenderImageFormat format;
                string            imageFormatText = context.Request.QueryString["itype"];
                if (!TryParseEnum <RenderImageFormat>(imageFormatText, true, out format))
                {
                    format = RenderImageFormat.Jpeg;
                }

                // Setup content-type and image format for saving
                ImageFormat imageFormat;
                switch (format)
                {
                case RenderImageFormat.Jpeg:
                    imageFormat = ImageFormat.Jpeg;
                    context.Response.ContentType = "image/jpeg";
                    break;

                case RenderImageFormat.Png:
                    imageFormat = ImageFormat.Png;
                    context.Response.ContentType = "image/png";
                    break;

                default:
                    throw new ArgumentException(
                              "Unexpected rendering image format encountered.");
                }

                // If we can find an encoder for the image type then attempt
                //	to set top quality and monochrome colour depth.
                ImageCodecInfo codecInfo = ImageCodecInfo.GetImageEncoders()
                                           .FirstOrDefault((item) => item.FormatID == imageFormat.Guid);
                EncoderParameters codecParameters = null;
                if (codecInfo != null)
                {
                    // Two parameters; maximum quality and monochrome
                    codecParameters          = new EncoderParameters(2);
                    codecParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    codecParameters.Param[1] = new EncoderParameter(Encoder.ColorDepth, 2);
                }

                // Create instance of barcode rendering engine
                BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(symbology);
                using (Image image = drawObject.Draw(textToRender, metrics))
                {
                    // Save image to the response stream directly
                    // TODO: Should the response have buffer enabled?
                    if (codecInfo == null)
                    {
                        image.Save(context.Response.OutputStream, imageFormat);
                    }
                    else
                    {
                        image.Save(context.Response.OutputStream, codecInfo, codecParameters);
                    }
                }

                // Set status and finalise request handling.
                context.Response.StatusCode = 200;
                context.Response.End();
            }
            catch (Exception)
            {
                // TODO: Log the error and return a 500...
                context.Response.StatusCode = 500;
                context.Response.End();
            }
        }
Пример #18
0
 // From msdn
 private static ImageCodecInfo GetEncoderInfo(String mimeType)
 {
     ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
     return(encoders.FirstOrDefault(t => t.MimeType == mimeType));
 }
Пример #19
0
        /// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="fontname">字体</param>
        /// <param name="fontsize">字体大小</param>
        public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            byte[] _ImageBytes = File.ReadAllBytes(WebHelper.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = WebHelper.GetMapPath(filename);

            Graphics g        = Graphics.FromImage(img);
            Font     drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF    crSize;

            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (float)img.Width * (float).01;
                ypos = (float)img.Height * (float).01;
                break;

            case 2:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = (float)img.Height * (float).01;
                break;

            case 3:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = (float)img.Height * (float).01;
                break;

            case 4:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 5:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 6:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                break;

            case 7:
                xpos = (float)img.Width * (float).01;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 8:
                xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;

            case 9:
                xpos = ((float)img.Width * (float).99) - crSize.Width;
                ypos = ((float)img.Height * (float).99) - crSize.Height;
                break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
        }
Пример #20
0
        static void FixMaps()
        {
            try
            {
                var db = new ZkDataContext();
                foreach (var r in db.Resources.Where(x => x.LastChange == null))
                {
                    r.LastChange = DateTime.UtcNow;
                }
                db.SubmitChanges();
                return;

                foreach (var resource in db.Resources.Where(x => x.TypeID == ResourceType.Map))//&&x.MapSizeSquared == null))
                {
                    var file = String.Format("{0}/{1}.metadata.xml.gz", @"d:\zero-k.info\www\Resources", resource.InternalName.EscapePath());
                    var map  = (Map) new XmlSerializer(typeof(Map)).Deserialize(new MemoryStream(File.ReadAllBytes(file).Decompress()));

                    resource.MapWidth  = map.Size.Width / 512;
                    resource.MapHeight = map.Size.Height / 512;

                    if (string.IsNullOrEmpty(resource.AuthorName))
                    {
                        if (!string.IsNullOrEmpty(map.Author))
                        {
                            resource.AuthorName = map.Author;
                        }
                        else
                        {
                            Console.WriteLine("regex test");
                            var m = Regex.Match(map.Description, "by ([\\w]+)", RegexOptions.IgnoreCase);
                            if (m.Success)
                            {
                                resource.AuthorName = m.Groups[1].Value;
                            }
                        }
                    }
                    Console.WriteLine("author: " + resource.AuthorName);


                    if (resource.MapIsSpecial == null)
                    {
                        resource.MapIsSpecial = map.ExtractorRadius > 120 || map.MaxWind > 40;
                    }
                    resource.MapSizeSquared = (map.Size.Width / 512) * (map.Size.Height / 512);
                    resource.MapSizeRatio   = (float)map.Size.Width / map.Size.Height;

                    var minimap = String.Format("{0}/{1}.minimap.jpg", @"d:\zero-k.info\www\Resources", resource.InternalName.EscapePath());

                    using (var im = Image.FromFile(minimap))
                    {
                        int w, h;

                        if (resource.MapSizeRatio > 1)
                        {
                            w = 96;
                            h = (int)(w / resource.MapSizeRatio);
                        }
                        else
                        {
                            h = 96;
                            w = (int)(h * resource.MapSizeRatio);
                        }

                        using (var correctMinimap = new Bitmap(w, h, PixelFormat.Format24bppRgb))
                        {
                            using (var graphics = Graphics.FromImage(correctMinimap))
                            {
                                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                graphics.DrawImage(im, 0, 0, w, h);
                            }

                            var jgpEncoder    = ImageCodecInfo.GetImageEncoders().First(x => x.FormatID == ImageFormat.Jpeg.Guid);
                            var encoderParams = new EncoderParameters(1);
                            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

                            var target = String.Format("{0}/{1}.thumbnail.jpg", @"d:\zero-k.info\www\Resources", resource.InternalName.EscapePath());
                            correctMinimap.Save(target, jgpEncoder, encoderParams);
                        }
                    }
                    Console.WriteLine(string.Format("{0}", resource.InternalName));
                }
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Пример #21
0
        public bool GetThumbnail(out string retCode)
        {
            bool retFlag = false;

            retCode = string.Empty;
            System.Drawing.Image oImg = null;
            try
            {
                oImg = System.Drawing.Image.FromFile(_pathPhysic + _imgFile);

                _bitMap = new Bitmap(oImg);

                if (_bitMap.Width > 100)
                {
                    // ===处理JPG质量的函数===
                    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   ici    = null;
                    foreach (ImageCodecInfo codec in codecs)
                    {
                        if (codec.MimeType == "image/jpeg")
                        {
                            ici = codec;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters();
                    ep.Param[0] =
                        new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality,
                            (long)this._level
                            );

                    this._icnWidth  = this._icnWidth < this._bitMap.Width ? this._icnWidth : this._bitMap.Width;
                    this._icnHeight = (int)((decimal)this._bitMap.Height * ((decimal)this._icnWidth / (decimal)this._bitMap.Width));

                    this._bitMap
                    .GetThumbnailImage(this._icnWidth, this._icnHeight, null, new System.IntPtr(0))
                    .Save(this._pathPhysic + this._neoFile, ici, ep);

                    retCode = "COMPLETE";
                }
                else
                {
                    retCode = "SMALL_SIZE";
                }
                oImg.Dispose();
                _bitMap.Dispose();
                retFlag = true;
            }
            catch (Exception err)
            {
                oImg.Dispose();
                _bitMap.Dispose();
                retFlag = false;
                retCode = err.ToString();
            }
            finally
            {
                oImg.Dispose();
                _bitMap.Dispose();
            }
            return(retFlag);
        }
Пример #22
0
        /// <summary>
        /// تبدیل تصاویر به یک تصویر چند صفحه ای
        /// MultiTiff
        /// </summary>
        public static Bitmap ConvertImagesToMultiTiff(Image[] pages)
        {
            if (pages.Length == 0)
            {
                return(null);
            }
            Bitmap bitmap = null;

            System.IO.MemoryStream memoryStream      = null;
            EncoderParameters      tiffEncoderParams = new EncoderParameters(1);

            try
            {
                bitmap = new Bitmap(pages[0].Width, pages[0].Height);
                bitmap.SetResolution(pages[0].HorizontalResolution, pages[0].VerticalResolution);

                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.DrawImageUnscaled(pages[0], 0, 0);
                graphics.Dispose();

                if (pages.Length > 1)
                {
                    memoryStream = new System.IO.MemoryStream();
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
                    ImageCodecInfo tiffEncoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
                    bitmap.Save(memoryStream, tiffEncoderInfo, tiffEncoderParams);
                }
                for (int i = 1; i < pages.Count(); i++)
                {
                    Bitmap newPage = new Bitmap(pages[i].Width, pages[i].Height);
                    newPage.SetResolution(pages[i].HorizontalResolution, pages[i].VerticalResolution);
                    Graphics g = Graphics.FromImage(newPage);
                    g.DrawImageUnscaled(pages[i], 0, 0);
                    g.Dispose();

                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);

                    bitmap.SaveAdd(newPage, tiffEncoderParams);
                    newPage.Dispose();
                }
                if (pages.Length > 1)
                {
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
                    bitmap.SaveAdd(tiffEncoderParams);
                    memoryStream.Flush();
                }
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                memoryStream = null;
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                bitmap = null;
            }
            finally
            {
                if (memoryStream != null)
                {
                    bitmap.Dispose();
                    bitmap = (Bitmap)Image.FromStream(memoryStream);
                }
            }
            return(bitmap);
        }
Пример #23
0
        private static string OpenSelectImageDialog(string previousPath = null)
        {
            var startPath      = ServiceLocator.Get <IResourceProviderService>().WorkPath;
            var dialogService  = ServiceLocator.Get <IFileDialogService>();
            var messageService = ServiceLocator.Get <IDialogBoxService>();
            var filter         = $"All image files ({string.Join(";", ImageCodecInfo.GetImageEncoders().Select(codec => codec.FilenameExtension).ToArray())})|{string.Join(";", ImageCodecInfo.GetImageEncoders().Select(codec => codec.FilenameExtension).ToArray())}";

            string filename = string.Empty;

            while (true)
            {
                if (!dialogService.ShowOpenFileDialog(ref filename, filter, previousPath ?? startPath))
                {
                    return(null);
                }

                if (filename.Contains(startPath))
                {
                    break;
                }

                messageService.ShowNativeDialog("Please select a file inside " + startPath, "Invalid selection");
            }

            var openSelectImageDialog = Utils.GetRelativePath(filename);

            return(openSelectImageDialog);
        }
Пример #24
0
        /// <summary>
        /// تبدیل یک تصویر چند صفحه ای به آرایه ای از بایت
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static byte[] GetMultiTiffImageBytes(Image image)
        {
            Bitmap bitmap = null;

            System.IO.MemoryStream memoryStream = null;
            int frameCount = image.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
            EncoderParameters tiffEncoderParams = new EncoderParameters(1);

            try
            {
                bitmap = new Bitmap(image.Width, image.Height);
                bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.DrawImageUnscaled(image, 0, 0);
                graphics.Dispose();

                if (frameCount > 1)
                {
                    memoryStream = new System.IO.MemoryStream();
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
                    ImageCodecInfo tiffEncoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
                    bitmap.Save(memoryStream, tiffEncoderInfo, tiffEncoderParams);
                }
                for (int i = 1; i < frameCount; i++)
                {
                    Bitmap newPage = new Bitmap(image.Width, image.Height);
                    newPage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    Graphics g = Graphics.FromImage(newPage);
                    image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
                    g.DrawImageUnscaled(image, 0, 0);
                    g.Dispose();

                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);

                    bitmap.SaveAdd(newPage, tiffEncoderParams);
                    newPage.Dispose();
                }
                if (frameCount > 1)
                {
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
                    bitmap.SaveAdd(tiffEncoderParams);
                    memoryStream.Flush();
                }
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                memoryStream = null;
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                bitmap = null;
                throw;
            }
            byte[] data = memoryStream.ToArray();
            if (memoryStream != null)
            {
                memoryStream.Dispose();
            }
            memoryStream = null;
            if (bitmap != null)
            {
                bitmap.Dispose();
            }
            bitmap = null;
            return(data);
        }
Пример #25
0
 public static string GetMimeType(this ImageFormat imageFormat)
 {
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
     return(codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType);
 }
Пример #26
0
        /// <summary>
        /// دریافت یک کپی از تصویر چند صفحه ای
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Bitmap GetMultiCopyOfImage(Image image)
        {
            Bitmap thumbImage = null;

            System.IO.MemoryStream memoryStream = null;
            int frameCount = image.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
            EncoderParameters tiffEncoderParams = new EncoderParameters(1);

            try
            {
                thumbImage = new Bitmap(image.Width, image.Height);
                thumbImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                Graphics graphics = Graphics.FromImage(thumbImage);
                graphics.DrawImageUnscaled(image, 0, 0);
                graphics.Dispose();

                if (frameCount > 1)
                {
                    memoryStream = new System.IO.MemoryStream();
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
                    ImageCodecInfo tiffEncoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
                    thumbImage.Save(memoryStream, tiffEncoderInfo, tiffEncoderParams);
                }
                for (int i = 1; i < frameCount; i++)
                {
                    image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
                    Bitmap newPage = new Bitmap(image.Width, image.Height);
                    newPage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    Graphics g = Graphics.FromImage(newPage);
                    g.DrawImageUnscaled(image, 0, 0);
                    g.Dispose();

                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);

                    thumbImage.SaveAdd(newPage, tiffEncoderParams);
                    newPage.Dispose();
                }
                if (frameCount > 1)
                {
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
                    thumbImage.SaveAdd(tiffEncoderParams);
                    memoryStream.Flush();
                }
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                memoryStream = null;
                if (thumbImage != null)
                {
                    thumbImage.Dispose();
                }
                thumbImage = null;
            }
            finally
            {
                if (memoryStream != null)
                {
                    thumbImage.Dispose();
                    thumbImage = (Bitmap)Image.FromStream(memoryStream);
                }
            }
            return(thumbImage);
        }
Пример #27
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>

        public bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);

            ImageFormat tFormat = iSource.RawFormat;

            int sW = 0, sH = 0;

            //按比例缩放

            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;

                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }

                else
                {
                    sH = dHeight;

                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }

            else
            {
                sW = tem_size.Width;

                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);

            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);

            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Dispose();
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    iSource.Dispose();
                    ob.Save(dFile, tFormat);
                }
            }
            catch (Exception ex)
            {
                LogHelper.CreateLogTxt(ex.Message);
                return(false);
            }
            finally
            {
                //iSource.Dispose();
                ob.Dispose();
            }
            return(true);
        }
Пример #28
0
        /// <summary>
        /// دریافت یک تصویر کوچک از تصویر اصلی
        /// </summary>
        /// <param name="image">تصویر اصلی</param>
        /// <param name="size">اندازه</param>
        /// <param name="backColor">رنگ پس زمینه</param>
        public static Image GetThumbnail(Image image, Size size, Color backColor)
        {
            if (size.Width <= 0 || size.Height <= 0)
            {
                throw new ArgumentException();
            }
            Image thumbImage = null;

            System.IO.MemoryStream memoryStream = null;
            int frameCount = image.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
            EncoderParameters tiffEncoderParams = new EncoderParameters(1);

            try
            {
                Size scaledSize = GetSizedImageBounds(image, size);
                thumbImage = new Bitmap(scaledSize.Width, scaledSize.Height);

                Graphics graphics = Graphics.FromImage(thumbImage);
                DrawImage(graphics, image, backColor, scaledSize);
                graphics.Dispose();

                if (frameCount > 1)
                {
                    memoryStream = new System.IO.MemoryStream();
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
                    ImageCodecInfo tiffEncoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
                    thumbImage.Save(memoryStream, tiffEncoderInfo, tiffEncoderParams);
                }
                for (int i = 1; i < frameCount; i++)
                {
                    Image newPage = new Bitmap(scaledSize.Width, scaledSize.Height);

                    Graphics g = Graphics.FromImage(newPage);
                    image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
                    DrawImage(g, image, backColor, scaledSize);
                    g.Dispose();

                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);

                    thumbImage.SaveAdd(newPage, tiffEncoderParams);
                    newPage.Dispose();
                }
                if (frameCount > 1)
                {
                    tiffEncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush);
                    thumbImage.SaveAdd(tiffEncoderParams);
                    memoryStream.Flush();
                }
            }
            catch
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
                memoryStream = null;
                if (thumbImage != null)
                {
                    thumbImage.Dispose();
                }
                thumbImage = null;
            }
            finally
            {
                if (memoryStream != null)
                {
                    thumbImage.Dispose();
                    thumbImage = Image.FromStream(memoryStream);
                }
            }
            return(thumbImage);
        }
Пример #29
0
        public static string CutPic(string fromFile, string toFile, int maxWidth, int maxHeight, int quality)
        {
            string result = toFile;

            fromFile = HttpContext.Current.Server.MapPath(fromFile);
            toFile   = HttpContext.Current.Server.MapPath(toFile);
            System.Drawing.Image image = System.Drawing.Image.FromFile(fromFile);
            if (image.Width <= maxWidth && image.Height <= maxHeight)
            {
                image.Save(toFile, ImageFormat.Jpeg);
            }
            else
            {
                double num  = (double)maxWidth / (double)maxHeight;
                double num2 = (double)image.Width / (double)image.Height;
                if (num == num2)
                {
                    System.Drawing.Image image2   = new Bitmap(maxWidth, maxHeight);
                    Graphics             graphics = Graphics.FromImage(image2);
                    graphics.DrawImage(image, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
                    image2.Save(toFile, ImageFormat.Jpeg);
                }
                else
                {
                    Rectangle            srcRect  = new Rectangle(0, 0, 0, 0);
                    Rectangle            destRect = new Rectangle(0, 0, 0, 0);
                    System.Drawing.Image image3;
                    Graphics             graphics2;
                    if (num > num2)
                    {
                        image3          = new Bitmap(image.Width, (int)Math.Floor((double)image.Width / num));
                        graphics2       = Graphics.FromImage(image3);
                        srcRect.X       = 0;
                        srcRect.Y       = (int)Math.Floor(((double)image.Height - (double)image.Width / num) / 2.0);
                        srcRect.Width   = image.Width;
                        srcRect.Height  = (int)Math.Floor((double)image.Width / num);
                        destRect.X      = 0;
                        destRect.Y      = 0;
                        destRect.Width  = image.Width;
                        destRect.Height = (int)Math.Floor((double)image.Width / num);
                    }
                    else
                    {
                        image3          = new Bitmap((int)Math.Floor((double)image.Height * num), image.Height);
                        graphics2       = Graphics.FromImage(image3);
                        srcRect.X       = (int)Math.Floor(((double)image.Width - (double)image.Height * num) / 2.0);
                        srcRect.Y       = 0;
                        srcRect.Width   = (int)Math.Floor((double)image.Height * num);
                        srcRect.Height  = image.Height;
                        destRect.X      = 0;
                        destRect.Y      = 0;
                        destRect.Width  = (int)Math.Floor((double)image.Height * num);
                        destRect.Height = image.Height;
                    }
                    graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics2.SmoothingMode     = SmoothingMode.HighQuality;
                    graphics2.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel);
                    System.Drawing.Image image2   = new Bitmap(maxWidth, maxHeight);
                    Graphics             graphics = Graphics.FromImage(image2);
                    graphics.DrawImage(image3, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, image3.Width, image3.Height), GraphicsUnit.Pixel);
                    ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   encoder       = null;
                    ImageCodecInfo[] array         = imageEncoders;
                    for (int i = 0; i < array.Length; i++)
                    {
                        ImageCodecInfo imageCodecInfo = array[i];
                        if (imageCodecInfo.MimeType == "image/jpeg")
                        {
                            encoder = imageCodecInfo;
                            break;
                        }
                    }
                    EncoderParameters encoderParameters = new EncoderParameters(1);
                    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
                    image2.Save(toFile, encoder, encoderParameters);
                    graphics.Dispose();
                    image2.Dispose();
                    graphics2.Dispose();
                    image3.Dispose();
                }
            }
            image.Dispose();
            return(result);
        }
Пример #30
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForSquare(this Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            Image initImage = Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if ((initImage.Width <= side) && (initImage.Height <= side))
            {
                initImage.Save(fileSaveUrl, ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高
                int initWidth  = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    Image    pickedImage;
                    Graphics pickedG;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initHeight, initHeight);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new Bitmap(initWidth, initWidth);
                        pickedG     = Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR   = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                Image    resultImage = new Bitmap(side, side);
                Graphics resultG     = Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode     = SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif"))
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);
                //释放关键质量控制所用资源
                ep.Dispose();
                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();
                //释放原始图片资源
                initImage.Dispose();
            }
        }