/// <summary>
        /// 使用方法调用GenerateHighThumbnail()方法即可
        /// 参数oldImagePath表示要被缩放的图片路径
        /// 参数newImagePath表示缩放后保存的图片路径
        /// 参数width和height分别是缩放范围宽和高
        /// </summary>
        /// <param name="oldImagePath"></param>
        /// <param name="newImagePath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height)
        {
            System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath);
            int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
            int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;

            System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage);
            //处理JPG质量的函数
            System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
            if (ici != null)
            {
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                bm.Save(newImagePath, ici, ep);
                //释放所有资源,不释放,可能会出错误。
                ep.Dispose();
                ep = null;
            }
            ici = null;
            bm.Dispose();
            bm = null;
            thumbnailImage.Dispose();
            thumbnailImage = null;
            oldImage.Dispose();
            oldImage = null;
        }
Exemple #2
0
        } // end of color

        //使用方法调用GenerateHighThumbnail()方法即可
        //参数oldImagePath表示要被缩放的图片路径
        //参数newImagePath表示缩放后保存的图片路径
        //参数width和height分别是缩放范围宽和高
        public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height)
        {
            System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath);
            int newWidth  = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width;
            int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height;

            //。。。。。。。。。。。
            System.Drawing.Image  thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            System.Drawing.Bitmap bm             = new System.Drawing.Bitmap(thumbnailImage);
            //处理JPG质量的函数
            System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
            if (ici != null)
            {
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                bm.Save(newImagePath, ici, ep);
                //释放所有资源,不释放,可能会出错误。
                ep.Dispose();
                ep = null;
            }
            ici = null;
            bm.Dispose();
            bm = null;
            thumbnailImage.Dispose();
            thumbnailImage = null;
            oldImage.Dispose();
            oldImage = null;
        }
 /// <summary>
 /// 保存图片
 /// </summary>
 /// <param name="image">Image 对象</param>
 /// <param name="savePath">保存路径</param>
 /// <param name="ici">指定格式的编解码参数</param>
 private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
 {
     //设置 原图片 对象的 EncoderParameters 对象
     System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1);
     parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100));
     image.Save(savePath, ici, parameters);
     parameters.Dispose();
 }
        /// <summary>
        /// 保存扫描的申请单
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private bool SaveScanImg(Bitmap bmp)
        {
            //创建一个扫描图像类
            ScanData oneScan = new ScanData();

            oneScan.申请ID      = _str申请ID;
            oneScan.扫描ID      = SqlHelper.GetNumGuid().ToString();
            oneScan.扫描信息.存储ID = 存储ID;
            oneScan.扫描信息.扫描人  = 扫描人;
            oneScan.扫描信息.扫描时间 = _scanModel.GetServerDate();
            oneScan.扫描信息.文件名  = Guid.NewGuid().ToString("N");
            oneScan.扫描信息.申请日期 = 申请日期;
            oneScan.扫描信息.CopyBasePro(oneScan);

            try
            {
                //保存临时文件
                var eps = new System.Drawing.Imaging.EncoderParameters(1);
                var ep  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
                eps.Param[0] = ep;
                var jpsEncoder = GetEncoder(ImageFormat.Jpeg);

                FTPFileHelp ftpHelper = new FTPFileHelp();
                initFTP(_dbQuery, 存储ID, out ftpHelper);

                string vPath   = ftpHelper.VPath + "//" + oneScan.扫描信息.申请日期.ToString("yyyyMMdd") + "//" + oneScan.申请ID + "//apply//";
                string tmpFile = System.Windows.Forms.Application.StartupPath + @"\Temp" + vPath.Replace("//", "\\");
                if (Directory.Exists(tmpFile) == false)
                {
                    Directory.CreateDirectory(tmpFile);
                }

                tmpFile = tmpFile + oneScan.扫描信息.文件名 + ".jpg";
                bmp.Save(tmpFile, jpsEncoder, eps);
                //释放资源
                ep.Dispose();
                eps.Dispose();

                //上传FTP
                FileInfo fi = new FileInfo(tmpFile);
                ftpHelper.MakeDirectory(vPath);
                if (ftpHelper.FileUpLoad(vPath + oneScan.扫描信息.文件名 + ".jpg", fi) == true)
                {
                    //存入数据库
                    _scanModel.SaveScanImage(oneScan);
                }
                else
                {
                    return(false);
                }
                //ftpHelper.disConnect(); 没有关闭连接的方法吗?
            }
            catch (Exception ex)
            {
                MsgBox.ShowException(ex, this);
            }
            return(true);
        }
Exemple #5
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        public void addWaterMark(string oldpath, string newpath)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);
                Bitmap   b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode     = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                if (IsWaterMark)
                {
                    switch (this.WMType)
                    {
                    case WaterMarkType.WM_IMAGE:     //水印图片
                        this.addWatermarkImage(g, _waterMarkImgPath, WMLocation, image.Width, image.Height);
                        break;

                    case WaterMarkType.WM_TEXT:    //水印文字
                        this.addWatermarkText(g, this.WaterMarkText, WMLocation, image.Width, image.Height);
                        break;
                    }

                    #region 降低图片质量
                    System.Drawing.Imaging.ImageCodecInfo    encoder       = GetEncoderInfo("image/jpeg");
                    System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                    encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80);
                    #endregion
                    b.Save(newpath, encoder, encoderParams);
                    encoderParams.Dispose();
                    b.Dispose();
                    image.Dispose();
                }
            }
            catch
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
            finally
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceImage"></param>
        /// <param name="fileSavePath"></param>
        /// <param name="quality"></param>
        /// <param name="imageFormat"></param>
        public static void Zoom(Image sourceImage, string fileSavePath , int quality , string imageFormat)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSavePath);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            //缩略图对象
            Image resultImage = new Bitmap(sourceImage.Width , sourceImage.Height );
            Graphics resultG = Graphics.FromImage(resultImage);
            //设置质量
            resultG.InterpolationMode = InterpolationMode.HighQualityBicubic;
            resultG.SmoothingMode = SmoothingMode.HighQuality;
            //用指定背景色清空画布
            resultG.Clear(Color.White);
            //绘制缩略图

            Rectangle sRect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
            Rectangle dRect = sRect;

            resultG.DrawImage( sourceImage , dRect, sRect, 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")
                if( i.MimeType == imageFormat )
                {
                    ici = i;
                }
            }
            EncoderParameters ep = new EncoderParameters(1);
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

            //保存缩略图
            resultImage.Save(fileSavePath , ici, ep);

            //释放关键质量控制所用资源
            ep.Dispose();

            //释放缩略图资源
            resultG.Dispose();
            resultImage.Dispose();

            //释放原始图片资源
            //initImage.Dispose();
        }
        /// <summary> 
        /// Saves an image as a jpeg image, with the given quality 
        /// </summary> 
        public static void SaveJpeg(this Bitmap image, string path, int quality)
        {
            if ((quality < 0) || (quality > 100))
            {
                string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
                throw new ArgumentOutOfRangeException(error);
            }

            var qualityParam = new EncoderParameter(Encoder.Quality, quality);
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            var encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            image.Save(path, jpegCodec, encoderParams);
            encoderParams.Dispose();
        }
Exemple #8
0
 public static void CreateThumbnail(string sourceFilename, string destFilename, int width, int height)
 {
     System.Drawing.Image image = System.Drawing.Image.FromFile(sourceFilename);
     if (image.Width <= width && image.Height <= height)
     {
         System.IO.File.Copy(sourceFilename, destFilename, true);
         image.Dispose();
     }
     else
     {
         int   width2  = image.Width;
         int   height2 = image.Height;
         float num     = (float)height / (float)height2;
         if ((float)width / (float)width2 < num)
         {
             num = (float)width / (float)width2;
         }
         width  = (int)((float)width2 * num);
         height = (int)((float)height2 * num);
         System.Drawing.Image    image2   = new System.Drawing.Bitmap(width, height);
         System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image2);
         graphics.Clear(System.Drawing.Color.White);
         graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
         graphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, width2, height2), System.Drawing.GraphicsUnit.Pixel);
         System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters();
         System.Drawing.Imaging.EncoderParameter  encoderParameter  = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
         encoderParameters.Param[0] = encoderParameter;
         System.Drawing.Imaging.ImageCodecInfo[] imageEncoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
         System.Drawing.Imaging.ImageCodecInfo   encoder       = null;
         for (int i = 0; i < imageEncoders.Length; i++)
         {
             if (imageEncoders[i].FormatDescription.Equals("JPEG"))
             {
                 encoder = imageEncoders[i];
                 break;
             }
         }
         image2.Save(destFilename, encoder, encoderParameters);
         encoderParameters.Dispose();
         encoderParameter.Dispose();
         image.Dispose();
         image2.Dispose();
         graphics.Dispose();
     }
 }
Exemple #9
0
        public void MergeTiffPages(string str_DestinationPath, string[] sourceFiles)
        {
            System.Drawing.Imaging.ImageCodecInfo codec = null;

            foreach (System.Drawing.Imaging.ImageCodecInfo cCodec in System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders())
            {
                if (cCodec.CodecName == "Built-in TIFF Codec")
                {
                    codec = cCodec;
                }
            }

            try
            {
                System.Drawing.Imaging.EncoderParameters imagePararms = new System.Drawing.Imaging.EncoderParameters(1);
                imagePararms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);

                if (sourceFiles.Length == 1)
                {
                    System.IO.File.Copy((string)sourceFiles[0], str_DestinationPath, true);
                }
                else if (sourceFiles.Length >= 1)
                {
                    System.Drawing.Image DestinationImage = (System.Drawing.Image)(new System.Drawing.Bitmap((string)System.Configuration.ConfigurationSettings.AppSettings["Path"] + sourceFiles[0]));

                    DestinationImage.Save(str_DestinationPath, codec, imagePararms);

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

                    for (int i = 0; i < sourceFiles.Length - 1; i++)
                    {
                        System.Drawing.Image img = (System.Drawing.Image)(new System.Drawing.Bitmap((string)sourceFiles[i]));

                        DestinationImage.SaveAdd(img, imagePararms);
                        img.Dispose();
                    }

                    imagePararms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.Flush);
                    DestinationImage.SaveAdd(imagePararms);
                    imagePararms.Dispose();
                    DestinationImage.Dispose();
                }
            }
            catch (Exception ex)
            { }
        }
Exemple #10
0
 public static void CreateThumbnail(string sourceFilename, string destFilename, int width, int height)
 {
     Image image = Image.FromFile(sourceFilename);
     if ((image.Width <= width) && (image.Height <= height))
     {
         File.Copy(sourceFilename, destFilename, true);
         image.Dispose();
     }
     else
     {
         int num = image.Width;
         int num2 = image.Height;
         float num3 = ((float)height) / ((float)num2);
         if ((((float)width) / ((float)num)) < num3)
         {
             num3 = ((float)width) / ((float)num);
         }
         width = (int)(num * num3);
         height = (int)(num2 * num3);
         Image image2 = new Bitmap(width, height);
         Graphics graphics = Graphics.FromImage(image2);
         graphics.Clear(Color.White);
         graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
         graphics.SmoothingMode = SmoothingMode.HighQuality;
         graphics.DrawImage(image, new Rectangle(0, 0, width, height), new Rectangle(0, 0, num, num2), GraphicsUnit.Pixel);
         EncoderParameters encoderParams = new EncoderParameters();
         EncoderParameter parameter = new EncoderParameter(Encoder.Quality, 100L);
         encoderParams.Param[0] = parameter;
         ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
         ImageCodecInfo encoder = null;
         for (int i = 0; i < imageEncoders.Length; i++)
         {
             if (imageEncoders[i].FormatDescription.Equals("JPEG"))
             {
                 encoder = imageEncoders[i];
                 break;
             }
         }
         image2.Save(destFilename, encoder, encoderParams);
         encoderParams.Dispose();
         parameter.Dispose();
         image.Dispose();
         image2.Dispose();
         graphics.Dispose();
     }
 }
Exemple #11
0
        public void Execute(CommandContext context)
        {
            Bitmap bitmap = null;
            EncoderParameters encoderParams = null;
            EncoderParameter parameter = null;
            try
            {
                var temp = Environment.GetEnvironmentVariable("TEMP");
                var picPath = temp + "\\" + Guid.NewGuid() + ".bmp";

                var webcam = new WebCamUtility(context.Handle, 600, 480);
                webcam.StartWebCam();
                webcam.GrabImage(context.Handle, picPath);
                webcam.CloseWebcam();

                bitmap = new Bitmap(picPath);
                var codecInfo = GetCodecInfo("image/jpeg");
                var quality = Encoder.Quality;
                encoderParams = new EncoderParameters(1);
                const long num = 0x5fL;
                parameter = new EncoderParameter(quality, num);
                encoderParams.Param[0] = parameter;

                var newPicPath = picPath.Replace("bmp", "jpg");
                bitmap.Save(newPicPath, codecInfo, encoderParams);

                if (context.SendPhotoByEmail)
                {
                    SendComment(context, "#PCң����#���ڷ������WebCamץ�ĵ����ָ��Email�У����һ��ȥ���ա�");
                    SendPhotoByEmail(context, newPicPath);
                }
                else
                {
                    SendComment(context, "#PCң����#�����ϴ����WebCamץ�ģ�һ�Ὣ��������������΢���С�");
                    context.WeiboService.SendWeiboWithPicture("������ʹ��#PCң����#�����ҵ�WebCamץ�� " + DateTime.Now.ToLongTimeString(), newPicPath);
                }

            }
            finally
            {
                if (parameter != null) parameter.Dispose();
                if (encoderParams != null) encoderParams.Dispose();
                if (bitmap != null) bitmap.Dispose();
            }
        }
        public static void ConvertPngToJpeg(string sourceFilePath, string destinationFilePath)
        {
            try
            {
                ImageCodecInfo[] ImageCodecs = new ImageCodecInfo[0];
                EncoderParameters Encoder;
                Bitmap Bmpmages = new Bitmap(sourceFilePath);
                ImageCodecs = ImageCodecInfo.GetImageEncoders();
                Encoder = new EncoderParameters(1);

                Encoder.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100);

                Bmpmages.Save(destinationFilePath);

                Bmpmages.Dispose();
                Encoder.Dispose();
            }
            catch (Exception)
            {
            }
        }
Exemple #13
0
 public static byte[] CompressionImage(Stream fileStream, long quality)
 {
     using (System.Drawing.Image img = System.Drawing.Image.FromStream(fileStream))
     {
         using (Bitmap bitmap = new Bitmap(img))
         {
             ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
             System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
             EncoderParameters myEncoderParameters = new EncoderParameters(1);
             EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
             myEncoderParameters.Param[0] = myEncoderParameter;
             using (MemoryStream ms = new MemoryStream())
             {
                 bitmap.Save(ms, CodecInfo, myEncoderParameters);
                 myEncoderParameters.Dispose();
                 myEncoderParameter.Dispose();
                 return ms.ToArray();
             }
         }
     }
 }
        /// <summary>
        /// Returns an instance of EncodingParameters for jpeg compression. 
        /// </summary>
        /// <param name="quality">The quality to return the image at.</param>
        /// <returns>The encodingParameters for jpeg compression. </returns>
        public static EncoderParameters GetEncodingParameters(int quality)
        {
            EncoderParameters encoderParameters = null;
            try
            {
                // Create a series of encoder parameters.
                encoderParameters = new EncoderParameters(1);

                // Set the quality.
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
            }
            catch
            {
                if (encoderParameters != null)
                {
                    encoderParameters.Dispose();
                }
            }

            return encoderParameters;
        }
Exemple #15
0
        /// <SUMMARY>
        /// 生成缩略图//带压缩图片不压缩22k压缩2k
        /// </SUMMARY>
        /// <PARAM name="originalImagePath" />原始路径
        /// <PARAM name="thumbnailPath" />生成缩略图路径
        /// <PARAM name="width" />缩略图的宽
        /// <PARAM name="height" />缩略图的高
        //是否压缩图片质量
        public static void MakeThumbnail(Stream sFile, string thumbnailPath, int width, int height, bool Ys)
        {
            //获取原始图片
            Image originalImage = Image.FromStream(sFile);
            //缩略图画布宽高
            int towidth  = 0;
            int toheight = 0;

            if (originalImage.Width > 1800) //图片像素大于1800,则缩放四倍
            {
                width    = originalImage.Width / 4;
                height   = originalImage.Height / 4;
                towidth  = width;
                toheight = height;
            }
            else if (originalImage.Width > 800) //图片像素大于800,则缩放2倍
            {
                width    = originalImage.Width / 2;
                height   = originalImage.Height / 2;
                towidth  = width;
                toheight = height;
            }
            else  //图片不是太大,则保持原大小
            {
                towidth  = originalImage.Width; //width;
                toheight = originalImage.Height; //height;
                width    = towidth;
                height   = toheight;
            }
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量
            double multiple = 0;

            //获取宽长的或是高长与缩略图的倍数
            if (originalImage.Width >= originalImage.Height)
            {
                multiple = (double)originalImage.Width / (double)width;
            }
            else
            {
                multiple = (double)originalImage.Height / (double)height;
            }
            //上传的图片的宽和高小等于缩略图
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图
            else
            {
                //宽高按比例缩放
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个bmp图片,并设置缩略图大小.
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#FFF"));
            //在指定位置并且按指定大小绘制原图片的指定部分
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            if (Ys)
            {
                System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg");
                try
                {
                    if (encoder != null)
                    {
                        System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                        //设置 jpeg 质量为 60
                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)50);
                        bitmap.Save(thumbnailPath, encoder, encoderParams);
                        encoderParams.Dispose();
                    }
                }
                catch (System.Exception e)
                {
                    //throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
            else
            {
                try
                {
                    //获取图片类型
                    string fileExtension = ".jpg";
                    //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
                    switch (fileExtension)
                    {
                    case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;

                    case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;

                    case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;

                    case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                    }
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
        }
Exemple #16
0
 public System.IO.Stream Process(System.IO.Stream inputStream)
 {
     if (inputStream == null || !inputStream.CanRead)
     {
         throw new System.ArgumentException("inputStream isn't validate", "inputStream");
     }
     inputStream.Seek(0L, System.IO.SeekOrigin.Begin);
     bool flag = false;
     Image image = Image.FromStream(inputStream);
     ImageFormat rawFormat = image.RawFormat;
     if (ImageProcessor.IsGIFAnimation(image))
     {
         inputStream.Seek(0L, System.IO.SeekOrigin.Begin);
         return inputStream;
     }
     foreach (IImageFilter current in this.Filters)
     {
         bool flag2;
         image = current.Process(image, out flag2);
         if (flag2)
         {
             flag = true;
         }
     }
     if (!flag)
     {
         inputStream.Seek(0L, System.IO.SeekOrigin.Begin);
         return inputStream;
     }
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     if (rawFormat.Guid == ImageFormat.Gif.Guid)
     {
         image.Save(memoryStream, ImageFormat.Jpeg);
     }
     else
     {
         EncoderParameters encoderParameters = new EncoderParameters(1);
         encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)this.JpegQuality);
         ImageCodecInfo imageCodecInfo = ImageProcessor.GetImageCodecInfo(rawFormat);
         image.Save(memoryStream, imageCodecInfo, encoderParameters);
         encoderParameters.Dispose();
     }
     memoryStream.Seek(0L, System.IO.SeekOrigin.Begin);
     return memoryStream;
 }
Exemple #17
0
        /// <summary>
        /// Generate prieviews
        /// </summary>
        /// <param name="img"></param>
        protected void GeneratePreviews(Bitmap img)
        {
            int x = MediaFile.Width;
            int y = MediaFile.Height;

            ImageFormat fmt;
            string mime;
            GetPreviewFormat(out fmt, out mime);
            EncoderParameters eparams = new EncoderParameters(1);
            eparams.Param[0] = new EncoderParameter(Encoder.Quality,
                                                    Manager.PreviewQuality);
            ImageCodecInfo ici = Gfx.GetEncoderInfo(mime);
            bool gendefault = false;

            if (x > Manager.PreviewMinWidth || y > Manager.PreviewMinHeight) {
                //Log.Debug("### Generate previews for {0}\n", MediaFile.FullName);
                foreach (Preview p in Manager.Previews) {
                    if (x < p.Width && y < p.Height) {
                        if (p.Name == "medium")
                            gendefault = true;
                        continue;
                    }
                    PreviewFile pf = lowGenImg(ref img, p, fmt, mime, ici, eparams);
                    MediaFile.Previews.Add(pf);
                }
            }
            else {
                gendefault = true;
            }

            if (gendefault) {
                Preview p = new Preview();
                p.Width = img.Width;
                p.Height = img.Height;
                p.Name = "default";

                PreviewFile pf = lowGenImg(ref img, p, fmt, mime, ici, eparams);
                MediaFile.Previews.Add(pf);
            }

            eparams.Dispose();
            eparams = null;
            ici = null;
            fmt = null;
        }
Exemple #18
0
        public virtual void ThumbByCut(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality)
        {
            Image    source = null;
            Graphics gdiobj = null;

            System.Drawing.Imaging.EncoderParameters ep = null;
            Bitmap img = null;

            try
            {
                source = System.Drawing.Image.FromStream(sourceStream);
                if (source.Width == width && source.Height == height)
                {
                    //原图输出
                    source.Save(ouputStream, source.RawFormat);
                    return;
                }

                //先等比裁剪
                int tw = width;
                int th = height;
                if (tw == 0 && th != 0)
                {
                    tw = (int)(source.Width * (double)th / source.Height);
                }
                else if (th == 0 && tw != 0)
                {
                    th = (int)(source.Height * (double)width / source.Width);
                }
                else if (th == 0 && tw == 0)
                {
                    th = source.Height;
                    tw = source.Width;
                }

                int cutWidth  = 0;
                int cutHeight = 0;

                int bywWidth  = source.Width;
                int bywHeight = (int)(source.Width * (double)th / tw);
                if (bywHeight < 1)
                {
                    bywHeight = 1;
                }

                int byhWidth = (int)(source.Height * (double)tw / th);
                if (byhWidth < 1)
                {
                    byhWidth = 1;
                }
                int byhHeight = source.Height;


                if (bywHeight > source.Height)//如果根据宽度裁剪得到的高度超过原始高度
                {
                    cutWidth  = byhWidth;
                    cutHeight = byhHeight;
                }
                else if (byhWidth > source.Width) //如果根据高度裁剪得到的宽度高过原始宽度
                {
                    cutWidth  = bywWidth;
                    cutHeight = bywHeight;
                }
                else
                {
                    //如果两个依据都符合,则根据面积的大小判断,面积越大,精确度越高
                    if ((bywWidth * bywHeight) > (byhWidth * byhHeight))
                    {
                        cutWidth  = bywWidth;
                        cutHeight = bywHeight;
                    }
                    else
                    {
                        cutWidth  = byhWidth;
                        cutHeight = byhHeight;
                    }
                }

                //根据中心点,得到裁剪的起始地址
                int x = (int)((double)source.Width / 2 - (double)cutWidth / 2);
                int y = (int)((double)source.Height / 2 - (double)cutHeight / 2);
                if (x < 0)
                {
                    x = 0;
                }
                if (y < 0)
                {
                    y = 0;
                }

                //根据计算的值,开始裁剪
                using (Bitmap bitmap = new Bitmap(cutWidth, cutHeight, PixelFormat.Format32bppArgb))
                {
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        Rectangle destRect = new Rectangle(0, 0, cutWidth, cutHeight);
                        g.DrawImage(source, destRect, x, y, cutWidth, cutHeight, GraphicsUnit.Pixel);
                        using (MemoryStream ms = new MemoryStream())
                        {
                            bitmap.Save(ms, ImageFormat.Png);
                            source.Dispose();
                            source = Image.FromStream(ms);

                            //再缩放
                            ImageZip(cutWidth, cutHeight, ref width, ref height);

                            img = new Bitmap(width, height);
                            //img.SetResolution(72f, 72f);
                            img.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                            gdiobj = Graphics.FromImage(img);
                            gdiobj.CompositingQuality = CompositingQuality.HighQuality;
                            gdiobj.SmoothingMode      = SmoothingMode.HighQuality;
                            gdiobj.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                            gdiobj.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                            gdiobj.FillRectangle(new SolidBrush(Color.FromArgb(0, Color.White)), 0, 0, width, height);
                            Rectangle destrect = new Rectangle(0, 0, width, height);
                            gdiobj.DrawImage(source, destrect, 0, 0, source.Width,
                                             source.Height, GraphicsUnit.Pixel);
                            ep          = new System.Drawing.Imaging.EncoderParameters(1);
                            ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                            if (!highQuality)
                            {
                                img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png);
                            }
                            else
                            {
                                System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/png");
                                if (ici != null)
                                {
                                    img.Save(ouputStream, ici, ep);
                                }
                                else
                                {
                                    img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (source != null)
                {
                    source.Dispose();
                }
                if (gdiobj != null)
                {
                    gdiobj.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string fileName = context.Server.UrlDecode(context.Request["src"]);
            if (string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("缺少参数src.");
                return;
            }
            fileName = Server.MapPath("~/" + fileName);

            Stream fileStream = null;
            try
            {
                string wStr = context.Request["width"];
                string hStr = context.Request["height"];
                int width = 0, height = 0;
                if (!string.IsNullOrEmpty(wStr) && !string.IsNullOrEmpty(hStr))
                {
                    int.TryParse(wStr, out width);
                    int.TryParse(hStr, out height);
                }

                FileInfo fi = new FileInfo(fileName);
                if (!fi.Exists)
                {
                    context.Response.Write("图片不存在.");
                    return;
                }
                string contentType = getContentType(fi.Extension);
                context.Response.ContentType = contentType;

                //只能处理jpg及png图片格式,没有宽高参数不进行缩放处理
                if (width > 0 && height > 0 && (contentType.Contains("jpeg") || contentType.Contains("png")))
                {
                    Image image = Image.FromFile(fi.FullName);
                    int sWidth = image.Width, sHeight = image.Height;
                    int nWidth = 0, nHeight = 0;
                    if (sWidth > width || sHeight > height)
                    {
                        if (((double)sWidth / (double)sHeight) > ((double)width / (double)height))
                        {
                            //以宽度为基准缩小
                            if (sWidth > width)
                            {
                                nWidth = width;
                                nHeight = (int)(width * sHeight / (double)sWidth);
                            }
                            else
                            {
                                nWidth = sWidth;
                                nHeight = sHeight;
                            }
                        }
                        else
                        {
                            //以高度为基准缩小
                            if (sHeight > height)
                            {
                                nWidth = (int)(height * sWidth / (double)sHeight);
                                nHeight = height;
                            }
                            else
                            {
                                nWidth = sWidth;
                                nHeight = sHeight;
                            }
                        }

                        Bitmap bitmap = new Bitmap(nWidth, nHeight, PixelFormat.Format32bppArgb);
                        Graphics graphics = Graphics.FromImage(bitmap);
                        graphics.Clear(Color.White);
                        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;  //平滑处理
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  //缩放质量
                        graphics.DrawImage(image, new Rectangle(0, 0, nWidth, nHeight));
                        image.Dispose();

                        EncoderParameters parameters = new EncoderParameters(1);
                        parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)80));  //图片质量参数

                        fileStream = new MemoryStream();
                        bitmap.Save(fileStream, GetImageCodecInfo(contentType), parameters);
                        using (MemoryStream ms = new MemoryStream())
                        {
                            bitmap.Save(ms, GetImageCodecInfo(contentType), parameters);
                            context.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                        }
                        parameters.Dispose();
                        bitmap.Dispose();
                        return;
                    }
                    if (image != null)
                        image.Dispose();
                }
                else
                {
                    fileStream = new FileStream(fi.FullName, FileMode.Open);
                    byte[] bytes = new byte[(int)fileStream.Length];
                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();
                    context.Response.BinaryWrite(bytes);
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
            System.GC.Collect();
        }
Exemple #20
0
        /// <summary>
        /// 保留全图的缩放(但会使图像变形)
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <param name="ouputStream"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        /// <param name="highQuality"></param>
        public virtual void ThumbByFull(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality)
        {
            Image    source = null;
            Graphics gdiobj = null;

            System.Drawing.Imaging.EncoderParameters ep = null;
            Bitmap img = null;

            try
            {
                source = System.Drawing.Image.FromStream(sourceStream);
                if (source.Width == width && source.Height == height)
                {
                    //原图输出
                    source.Save(ouputStream, source.RawFormat);
                    return;
                }

                ImageZip(source.Width, source.Height, ref width, ref height);
                img = new Bitmap(width, height);
                //img.SetResolution(72f, 72f);
                img.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                gdiobj = Graphics.FromImage(img);
                gdiobj.CompositingQuality = CompositingQuality.HighQuality;
                gdiobj.SmoothingMode      = SmoothingMode.HighQuality;
                gdiobj.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                gdiobj.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                gdiobj.FillRectangle(new SolidBrush(Color.FromArgb(0, Color.White)), 0, 0, width, height);
                Rectangle destrect = new Rectangle(0, 0, width, height);
                gdiobj.DrawImage(source, destrect, 0, 0, source.Width,
                                 source.Height, GraphicsUnit.Pixel);
                ep          = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                if (!highQuality)
                {
                    img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/png");
                    if (ici != null)
                    {
                        img.Save(ouputStream, ici, ep);
                    }
                    else
                    {
                        img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (source != null)
                {
                    source.Dispose();
                }
                if (gdiobj != null)
                {
                    gdiobj.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (img != null)
                {
                    img.Dispose();
                }
            }
        }
        static byte[] CaptureWebPageBytesP(string body, int width, int height)
        {
            byte[] data;

            using (WebBrowser web = new WebBrowser())
            {
                web.ScrollBarsEnabled = false; // no scrollbars
                web.ScriptErrorsSuppressed = true; // no errors

                web.DocumentText = body;
                while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
                    System.Windows.Forms.Application.DoEvents();

                web.Width = web.Document.Body.ScrollRectangle.Width;
                web.Height = web.Document.Body.ScrollRectangle.Height;

                // a bitmap that we will draw to
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(web.Width, web.Height))
                {
                    // draw the web browser to the bitmap
                    web.DrawToBitmap(bmp, new Rectangle(web.Location.X, web.Location.Y, web.Width, web.Height));
                    // draw the web browser to the bitmap

                    GraphicsUnit units = GraphicsUnit.Pixel;
                    RectangleF destRect = new RectangleF(0F, 0F, width, height);
                    RectangleF srcRect = new RectangleF(0, 0, web.Width, web.Width * 1.5F);

                    Bitmap b = new Bitmap(width, height);
                    Graphics g = Graphics.FromImage((Image)b);
                    g.Clear(Color.White);
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    g.DrawImage(bmp, destRect, srcRect, units);
                    g.Dispose();

                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                    {
                        EncoderParameter qualityParam = null;
                        EncoderParameters encoderParams = null;
                        try
                        {
                            ImageCodecInfo imageCodec = null;
                            imageCodec = GetEncoderInfo("image/jpeg");

                            qualityParam = new EncoderParameter(Encoder.Quality, 100L);

                            encoderParams = new EncoderParameters(1);
                            encoderParams.Param[0] = qualityParam;
                            b.Save(stream, imageCodec, encoderParams);
                        }
                        catch (Exception)
                        {
                            throw new Exception();
                        }
                        finally
                        {
                            if (encoderParams != null) encoderParams.Dispose();
                            if (qualityParam != null) qualityParam.Dispose();
                        }
                        b.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Position = 0;
                        data = new byte[stream.Length];
                        stream.Read(data, 0, (int)stream.Length);
                    }
                }
            }
            return data;
        }
        byte [] GridTexture (string uri)
        {
            byte [] jpeg = new byte [0];
            var imageUUID = uri;

            // check for bogies
            if (imageUUID == "" || imageUUID == UUID.Zero.ToString ())
                return jpeg;

            IAssetService m_AssetService = m_registry.RequestModuleInterface<IAssetService> ();

            using (MemoryStream imgstream = new MemoryStream ()) {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte [] mapasset = m_AssetService.GetData (imageUUID);

                if (mapasset != null) {
                    // Decode image to System.Drawing.Image
                    Image image;
                    ManagedImage managedImage;
                    var myEncoderParameters = new EncoderParameters ();
                    myEncoderParameters.Param [0] = new EncoderParameter (System.Drawing.Imaging.Encoder.Quality, 75L);
                    if (OpenJPEG.DecodeToImage (mapasset, out managedImage, out image)) {
                        // Save to bitmap
                        var texture = ResizeBitmap (image, 256, 256);
                        try {
                            var encInfo = GetEncoderInfo ("image/jpeg");
                            if (encInfo != null)
                                texture.Save (imgstream, encInfo, myEncoderParameters);

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray ();
                        } catch {
                            MainConsole.Instance.Debug ("[API]: GridTexture request exception");
                        }
                    }
                    myEncoderParameters.Dispose ();
                    if (image != null)
                        image.Dispose ();
                }
            }

            if (jpeg.Length > 0)
                return jpeg;

            // no UUID here so...
            var nouuid = "html/images/icons/no_image.png";
            try {
                return File.ReadAllBytes (nouuid);
            } catch {
                MainConsole.Instance.Debug ("[API]: GridTexture fallback exception. 'no_image.jpg' does not exist?");
            }

            return new byte [0];
        }
Exemple #23
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <remarks>吴剑 2010-11-23</remarks>
        /// <param name="postedFile">原图HttpPostedFile对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

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

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

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

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.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, System.Drawing.GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode = System.Drawing.Drawing2D.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, System.Drawing.GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

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

                //缩略图对象
                System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), 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);

                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
            }
        }
Exemple #24
0
        public static void SaveAsHightQualityJPEG(Bitmap bmp, string fullFileNamePath)
        {
            ImageCodecInfo myImageCodecInfo = null;
            System.Drawing.Imaging.Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            if (bmp != null && string.IsNullOrEmpty(fullFileNamePath) == false)
            {
                // Get an ImageCodecInfo object that represents the JPEG codec.
                ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
                for (int j = 0; j < encoders.Length; ++j)
                {
                    if (encoders[j].MimeType == "image/jpeg")
                    {
                        myImageCodecInfo = encoders[j];
                        break;
                    }
                }

                // Create an Encoder object based on the GUID
                // for the Quality parameter category.
                myEncoder = System.Drawing.Imaging.Encoder.Quality;

                // Create an EncoderParameters object.
                // An EncoderParameters object has an array of EncoderParameter
                // objects. In this case, there is only one
                // EncoderParameter object in the array.
                myEncoderParameters = new EncoderParameters(1);

                // Save the bitmap as a JPEG file with quality level 25.
                myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                myEncoderParameters.Param[0] = myEncoderParameter;

                //--Save Bmp as JPEG
                //bmp.SetResolution(120F, 120F);

                bmp.Save(fullFileNamePath, myImageCodecInfo, myEncoderParameters);
                //bmp.SetResolution(96F, 96F);
                myEncoderParameters.Dispose();
            }
        }
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        public void addWaterMark(string oldpath, string newpath)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);
                Bitmap b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                if (IsWaterMark)
                {
                    switch (this.WMType)
                    {

                        case WaterMarkType.WM_IMAGE: //水印图片
                            this.addWatermarkImage(g, _waterMarkImgPath, WMLocation, image.Width, image.Height);
                            break;

                        case WaterMarkType.WM_TEXT://水印文字
                            this.addWatermarkText(g, this.WaterMarkText, WMLocation, image.Width, image.Height);
                            break;
                    }

                    #region 降低图片质量
                    System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg");
                    System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                    encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80);
                    #endregion
                    b.Save(newpath, encoder, encoderParams);
                    encoderParams.Dispose();
                    b.Dispose();
                    image.Dispose();
                }
            }
            catch
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
            finally
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bmpUpload"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool RewriteImageFix(Bitmap bmpUpload, int width, int height, string filename)
        {
            try
            {
                // nếu kích cỡ hình nhỏ hơn kích cỡ mong muốn thumbnail thì không cần thumbnail
                //if (bmpUpload.Width <= width && bmpUpload.Height <= height)
                //{
                //    return RewriteImage(bmpUpload, filename);
                //}

                #region Caculate thumb width, height
                int widthTh, heightTh;
                float widthOrig, heightOrig;
                float fx, fy, f;

                // retain aspect ratio
                widthOrig = bmpUpload.Width;
                heightOrig = bmpUpload.Height;
                // subsample factors
                fx = widthOrig / width;
                fy = heightOrig / height;
                // must fit in thumbnail size
                f = Math.Max(fx, fy);
                if (f < 1) f = 1;
                // Recalculate thumbnail size
                widthTh = (int)(widthOrig / f);
                heightTh = (int)(heightOrig / f);

                float beginX = (width - widthTh) / 2;
                float beginY = (height - heightTh) / 2;
                #endregion

                Bitmap bmpSave = new Bitmap(width, height);

                Graphics graph = Graphics.FromImage(bmpSave);
                graph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graph.Clear(Color.Transparent);
                graph.DrawImage(bmpUpload, beginX, beginY, widthTh, heightTh);

                string contentType = "image/png";
                ImageCodecInfo codec = GetEncoderInfo(contentType);
                if (codec == null)
                    codec = FindEncoder(ImageFormat.Png);
                EncoderParameters eps = new EncoderParameters();
                eps.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
                bmpSave.Save(filename, codec, eps);
                bmpSave.Dispose();

                //Finish
                graph.Dispose();
                eps.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="originalImage"></param>
        /// <param name="configs"></param>
        public static void MakeThumbnail(System.Drawing.Image originalImage, IList<ThumbConfig> configs)
        {
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            foreach (ThumbConfig config in configs)
            {

                int towidth = config.Width;
                int toheight = config.Height;

                switch (config.Mode)
                {
                    case ThumbnailMode.FixedHeightAndWidth:

                        break;
                    case ThumbnailMode.FixedBox:
                        float sx = (float)config.Width / (float)ow;
                        float sy = (float)config.Height / (float)oh;
                        float scale = Math.Min(1, Math.Min(sx, sy));
                        towidth = (int)(ow * scale);
                        toheight = (int)(oh * scale);
                        break;
                    case ThumbnailMode.FixedHeightAndWidthByPercent:
                        toheight = originalImage.Height * config.Width / originalImage.Width;
                        break;
                    case ThumbnailMode.FixedWidthAndHeightByPercent:
                        towidth = originalImage.Width * config.Height / originalImage.Height;
                        break;
                    case ThumbnailMode.Cut:
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * config.Height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    case ThumbnailMode.PercentByLowLength:
                        int newwidth = config.Width;
                        int newheight = 0;

                        if (originalImage.Width > 0 && originalImage.Height > 0)
                        {
                            if (originalImage.Width / originalImage.Height >= 1)
                            {
                                if (originalImage.Width > newwidth)
                                {
                                    newheight = originalImage.Height * newwidth / originalImage.Width;
                                }
                                else
                                {
                                    newwidth = originalImage.Width;
                                    newheight = originalImage.Height;
                                }
                            }
                            else
                            {
                                if (originalImage.Height > newwidth)
                                {
                                    newheight = newwidth;
                                    newwidth = (originalImage.Width * newwidth) / originalImage.Height;
                                }
                                else
                                {
                                    newwidth = originalImage.Width;
                                    newheight = originalImage.Height;
                                }
                            }
                        }

                        towidth = newwidth;
                        toheight = newheight;
                        //config.Mode = ThumbnailMode.HeightAndWidth;
                        break;
                    default:
                        break;
                }

                config.Width = towidth;
                config.Height = toheight;

                //new Bitmap instance
                Image bitmap = new Bitmap(towidth, toheight);

                //new Graphics instance
                Graphics g = Graphics.FromImage(bitmap);

                //set InterpolationMode
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //set CompositingQuality
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                //set HighQuality ,low speed SmoothingMode
                g.SmoothingMode = SmoothingMode.AntiAlias;

                //clear the Graphics and fill with Transparent background color

                if (config.IsPng)
                    g.Clear(Color.Transparent);
                else
                    g.Clear(Color.White);

                // render
                g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                new System.Drawing.Rectangle(x, y, ow, oh),
                System.Drawing.GraphicsUnit.Pixel);

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

                foreach (ImageCodecInfo codec in codecs)
                {

                    if (config.IsPng)
                    {
                        if (codec.MimeType.IndexOf("png") > -1)
                        {
                            ici = codec;
                        }
                    }
                    else
                    {
                        if (codec.MimeType.IndexOf("jpeg") > -1)
                        {
                            ici = codec;
                        }
                    }
                }

                var myEncoder = Encoder.Quality;
                var myEncoderParameters = new EncoderParameters(1);

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

                // 在这里设置图片的质量等级为95L.
                var myEncoderParameter = new EncoderParameter(myEncoder, 95L);

                myEncoderParameters.Param[0] = myEncoderParameter;

                try
                {
                    // System.Drawing.Imaging.ImageFormat.Jpeg
                    bitmap.Save(config.Path, ici, myEncoderParameters);
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    myEncoderParameter.Dispose();
                    myEncoderParameters.Dispose();

                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
        }
Exemple #28
0
 /// <summary>
 /// 高质量保存图片
 /// </summary>
 private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
 {
     // 设置 原图片 对象的 EncoderParameters 对象
     EncoderParameters parms = new EncoderParameters(1);
     EncoderParameter parm = new EncoderParameter(Encoder.Quality, ((long)95));
     parms.Param[0] = parm;
     try
     {
         image.Save(savePath, ici, parms);
     }
     catch
     {
     }
     parms.Dispose();
 }
Exemple #29
0
        protected override void SaveImage(Stream stream, Image image)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            myImageCodecInfo = GetEncoderInfo(EncoderType);
            myEncoder = Encoder.Quality;
            myEncoderParameters = new EncoderParameters(EncoderParameterCount);
            myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
            myEncoderParameters.Param[0] = myEncoderParameter;

            try
            {
                image.Save(stream, myImageCodecInfo, myEncoderParameters);
            }
            finally
            {
                myEncoderParameters.Dispose();
                myEncoderParameter.Dispose();
            }
        }
Exemple #30
0
    /// <SUMMARY>
    /// 生成缩略图//带压缩图片不压缩22k压缩2k
    /// </SUMMARY>
    /// <PARAM name="originalImagePath" />原始路径
    /// <PARAM name="thumbnailPath" />生成缩略图路径
    /// <PARAM name="width" />缩略图的宽
    /// <PARAM name="height" />缩略图的高
    //是否压缩图片质量
    public void MakeThumbnail(HttpPostedFileBase originalImageFile, string thumbnailPath, int width, int height, bool Ys)
    {
        //获取原始图片
        System.Drawing.Image originalImage = System.Drawing.Image.FromStream(originalImageFile.InputStream);
        //缩略图画布宽高
        int towidth  = width;
        int toheight = height;
        //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
        int x  = 0;
        int y  = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;
        //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
        int bg_x = 0;
        int bg_y = 0;
        int bg_w = towidth;
        int bg_h = toheight;
        //倍数变量
        double multiple = 0;

        //获取宽长的或是高长与缩略图的倍数
        if (originalImage.Width >= originalImage.Height)
        {
            multiple = (double)originalImage.Width / (double)width;
        }
        else
        {
            multiple = (double)originalImage.Height / (double)height;
        }
        //上传的图片的宽和高小等于缩略图
        if (ow <= width && oh <= height)
        {
            //缩略图按原始宽高
            bg_w = originalImage.Width;
            bg_h = originalImage.Height;
            //空白部分用背景色填充
            bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
            bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
        }
        //上传的图片的宽和高大于缩略图
        else
        {
            //宽高按比例缩放
            bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
            bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
            //空白部分用背景色填充
            bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
            bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
        }
        //新建一个bmp图片,并设置缩略图大小.
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //清空画布并设置背景色
        g.Clear(System.Drawing.ColorTranslator.FromHtml("#FFF"));
        //在指定位置并且按指定大小绘制原图片的指定部分
        //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素
        g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

        if (Ys)
        {
            System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg");
            try
            {
                if (encoder != null)
                {
                    System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1);
                    //设置 jpeg 质量为 60
                    encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)60);
                    bitmap.Save(thumbnailPath, encoder, encoderParams);
                    encoderParams.Dispose();
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        else
        {
            try
            {
                Bitmap bmp = new Bitmap(originalImageFile.InputStream);
                Image  img = (Image)bmp;
                //新建第二个bitmap类型的bmp2变量,这里是根据程序需要设置的。
                Bitmap bmp2 = new Bitmap(1024, 768, PixelFormat.Format16bppRgb555);
                //将第一个bmp拷贝到bmp2中
                Graphics draw = Graphics.FromImage(bmp2);
                draw.DrawImage(bmp, 0, 0);
                draw.Dispose();
                bmp.Dispose(); //释放bmp文件资源
                img.Dispose(); //释放bmp文件资源
                Image img1 = (Image)bmp2;
                //获取图片类型
                string fileExtension = System.IO.Path.GetExtension(originalImageFile.FileName).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
                switch (fileExtension)
                {
                case ".gif": img1.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;

                case ".jpg": img1.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;

                case ".bmp": img1.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;

                case ".png": img1.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    }
Exemple #31
0
		public void SaveToJpeg(string filename, int exifWidth, int exifHeight, byte quality)
		{
			if(channelFormat==Format.RGBA)
			{
				ConvertToRGB().SaveToJpeg(filename, exifWidth, exifHeight);
				return;
			}

			if(channelFormat!=Format.RGB) throw new Exception("Only rgb images can be saved by SaveToJpeg.");

			Bitmap bmp=new Bitmap((int)width, (int)height, PixelFormat.Format24bppRgb);

			BitmapData data=bmp.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

			if(((int)width*3)==data.Stride)
			{
				Marshal.Copy(imageData, 0, data.Scan0, (int)(width*height*3));
			}
			else
			{
				if(IntPtr.Size==4)
				{
					for(uint i=0; i<height; i++)
					{
						Marshal.Copy(imageData, (int)(width*3*i), (IntPtr)(data.Scan0.ToInt32()+(int)(i*data.Stride)), (int)(width*3));
					}
				}
				else if(IntPtr.Size==8)
				{
					for(uint i=0; i<height; i++)
					{
						Marshal.Copy(imageData, (int)(width*3*i), (IntPtr)(data.Scan0.ToInt64()+(long)(i*data.Stride)), (int)(width*3));
					}
				}
			}
			bmp.UnlockBits(data);
			data=null;

			if(exifWidth>0&&exifHeight>0)
			{
				PropertyItem o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);

				byte[] buff=Encoding.ASCII.GetBytes("ASCII\0\0\0"+exifWidth+"x"+exifHeight);
				o.Id=0x9286;
				o.Type=7;
				o.Len=buff.Length;
				o.Value=buff;
				bmp.SetPropertyItem(o);

				o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
				o.Id=0x100;
				o.Type=4;
				o.Len=4;
				o.Value=BitConverter.GetBytes((uint)exifWidth);
				bmp.SetPropertyItem(o);

				o=(PropertyItem)Activator.CreateInstance(typeof(PropertyItem), true);
				o.Id=0x101;
				o.Type=4;
				o.Len=4;
				o.Value=BitConverter.GetBytes((uint)exifHeight);
				bmp.SetPropertyItem(o);
			}

			if(quality>100) quality=100;

			EncoderParameters encoderParameters=new EncoderParameters(1);
			encoderParameters.Param[0]=new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
			bmp.Save(filename, jpegImageCodecInfo, encoderParameters);
			encoderParameters.Dispose();
			bmp.Dispose();
			bmp=null;
		}
Exemple #32
0
        private void SaveJpegImage(Stream stream, Image image)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            myImageCodecInfo = GetEncoderInfo(EncoderType);
            myEncoder = Encoder.Quality;
            myEncoderParameters = new EncoderParameters(EncoderParameterCount);
            myEncoderParameter = new EncoderParameter(myEncoder, PluginSettings.ImageQuality);
            myEncoderParameters.Param[0] = myEncoderParameter;

            try
            {
                image.Save(stream, myImageCodecInfo, myEncoderParameters);
            }
            finally
            {
                myEncoderParameters.Dispose();
                myEncoderParameter.Dispose();
            }
        }
Exemple #33
0
 /// <summary>
 /// 保存图片
 /// </summary>
 /// <param name="image">Image 对象</param>
 /// <param name="savePath">保存路径</param>
 /// <param name="ici">指定格式的编解码参数</param>
 private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
 {
     //设置 原图片 对象的 EncoderParameters 对象
     EncoderParameters parameters = new EncoderParameters(1);
     parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100));
     image.Save(savePath, ici, parameters);
     parameters.Dispose();
 }
        public byte [] OnHTTPGetMapImage (string path, Stream request, OSHttpRequest httpRequest,
                                        OSHttpResponse httpResponse)
        {
            MainConsole.Instance.Debug ("[World map]: Sending map image jpeg");
            byte [] jpeg = new byte [0];

            MemoryStream imgstream = new MemoryStream ();
            Bitmap mapTexture;
            Image image = null;

            try {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                imgstream = new MemoryStream ();

                // non-async because we know we have the asset immediately.
                byte [] mapasset =
                    m_scene.AssetService.GetData (m_scene.RegionInfo.RegionSettings.TerrainImageID.ToString ());
                if (mapasset != null) {
                    image = m_scene.RequestModuleInterface<IJ2KDecoder> ().DecodeToImage (mapasset);
                    // Decode image to System.Drawing.Image
                    if (image != null) {
                        // Save to bitmap
                        mapTexture = (Bitmap)image;

                        EncoderParameters myEncoderParameters = new EncoderParameters ();
                        myEncoderParameters.Param [0] = new EncoderParameter (Encoder.Quality, 95L);
                        var encInfo = GetEncoderInfo ("image/jpeg");

                        if (encInfo != null) {
                            // Save bitmap to stream
                            mapTexture.Save (imgstream, encInfo, myEncoderParameters);
                        }
                        myEncoderParameters.Dispose ();

                        // Write the stream to a byte array for output
                        jpeg = imgstream.ToArray ();
                    }
                }
            } catch (Exception) {
                // Dummy!
                MainConsole.Instance.Warn ("[World map]: Unable to generate Map image");
            } finally {
                // Reclaim memory, these are unmanaged resources
                // If we encountered an exception, one or more of these will be null
                if (image != null)
                    image.Dispose ();

                imgstream.Close ();
            }

            httpResponse.ContentType = "image/jpeg";
            return jpeg;
        }
        byte [] ConvertTextureData (AssetBase texture, string format)
        {
            MainConsole.Instance.DebugFormat ("[AssetCAPS]: Converting texture {0} to {1}", texture.ID, format);
            byte [] data = new byte [0];

            MemoryStream imgstream = new MemoryStream ();
            Image image = null;

            try {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
                image = m_j2kDecoder.DecodeToImage (texture.Data);
                if (image == null)
                    return data;
                // Save to bitmap
                image = new Bitmap (image);

                EncoderParameters myEncoderParameters = new EncoderParameters ();
                myEncoderParameters.Param [0] = new EncoderParameter (Encoder.Quality, 95L);

                // Save bitmap to stream
                try {
                    ImageCodecInfo codec = GetEncoderInfo ("image/" + format);

                    if (codec != null) {
                        image.Save (imgstream, codec, myEncoderParameters);
                        // Write the stream to a byte array for output
                        data = imgstream.ToArray ();
                    } else
                        MainConsole.Instance.WarnFormat ("[AssetCAPS]: No such codec {0}", format);
                } catch {
                    MainConsole.Instance.ErrorFormat ("[AssetCAPS]: Unable to retrieve codec {0}", format);
                }
                myEncoderParameters.Dispose ();
            } catch (Exception e) {
                MainConsole.Instance.WarnFormat ("[AssetCAPS]: Unable to convert texture {0} to {1}: {2}", texture.ID,
                                                format, e.Message);
            } finally {
                // Reclaim memory, these are unmanaged resources
                // If we encountered an exception, one or more of these will be null

                if (image != null)
                    image.Dispose ();

                imgstream.Close ();
            }

            return data;
        }
        byte[] CacheMapTexture(int maplayer, int regionX, int regionY, Bitmap mapTexture, bool forced = false)
        {
            if (!forced && IsStaticBlank(mapTexture))
                return m_blankRegionTileData;

            byte[] jpeg;
            EncoderParameters myEncoderParameters = new EncoderParameters();
            myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);

            using (MemoryStream imgstream = new MemoryStream())
            {
                var encInfo = GetEncoderInfo ("image/jpeg");
                if (encInfo != null) {
                    // Save bitmap to stream
                    lock (mapTexture)
                        mapTexture.Save (imgstream, encInfo, myEncoderParameters);
                }
                // Write the stream to a byte array for output
                jpeg = imgstream.ToArray ();

            }

            myEncoderParameters.Dispose ();
            SaveCachedImage(maplayer, regionX, regionY, jpeg);
            return jpeg;
        }
Exemple #37
0
 /// <summary>
 /// ����ͼƬ
 /// </summary>
 /// <param name="image">Image ����</param>
 /// <param name="savePath">����·��</param>
 /// <param name="ici">ָ����ʽ�ı�������</param>
 private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
 {
     //���� ԭͼƬ ����� EncoderParameters ����
     EncoderParameters parameters = new EncoderParameters(1);
     parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long) 100));
     image.Save(savePath, ici, parameters);
     parameters.Dispose();
 }
Exemple #38
0
        /// <summary>
        /// 壓縮圖片 /// </summary>
        /// <param name="fileStream">圖片流</param>
        /// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param>
        /// <returns></returns>
        public static byte[] CompressionImage(Image img, long quality)
        {
            using (Bitmap bitmap = new Bitmap(img))
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo CodecInfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        CodecInfo = arrayICI[x];
                        //設置jpg
                        break;
                    }
                }

                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                using (MemoryStream ms = new MemoryStream())
                {
                    bitmap.Save(ms, CodecInfo, myEncoderParameters);
                    myEncoderParameters.Dispose();
                    myEncoderParameter.Dispose();
                    return ms.ToArray();
                }
            }
        }
        void ExportArchiveImage (UUID imageUUID, string archiveName, string filePath)
        {
            byte [] jpeg;

            using (MemoryStream imgstream = new MemoryStream ()) {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte [] imageAsset = assetService.GetData (imageUUID.ToString ());

                if (imageAsset != null) {
                    // Decode image to System.Drawing.Image
                    Image image;
                    ManagedImage managedImage;
                    if (OpenJPEG.DecodeToImage (imageAsset, out managedImage, out image)) {
                        // Save to bitmap
                        using (Bitmap texture = ResizeBitmap (image, 256, 256, archiveName)) {
                            EncoderParameters myEncoderParameters = new EncoderParameters ();
                            myEncoderParameters.Param [0] = new EncoderParameter (Encoder.Quality, 75L);

                            // Save bitmap to stream
                            var encInfo = GetEncoderInfo ("image/jpeg");
                            if (encInfo != null)
                                texture.Save (imgstream, encInfo, myEncoderParameters);
                            myEncoderParameters.Dispose ();

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray ();

                            // save image
                            string fileName = archiveName + ".jpg";
                            string fullPath = Path.Combine (filePath, fileName);
                            File.WriteAllBytes (fullPath, jpeg);

                        }
                        image.Dispose ();
                    }
                }
            }
        }
        public void RegenerateMaptile (string ID, byte [] data)
        {
            MemoryStream imgstream = new MemoryStream ();
            Bitmap mapTexture = null;
            Image image = null;

            try {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                imgstream = new MemoryStream ();

                image = m_scene.RequestModuleInterface<IJ2KDecoder> ().DecodeToImage (data);
                // Decode image to System.Drawing.Image
                if (image != null) {
                    // Save to bitmap
                    mapTexture = new Bitmap (image);
                    mapTexture = OverlayBitmapText (mapTexture, "Region");

                    EncoderParameters myEncoderParameters = new EncoderParameters ();
                    myEncoderParameters.Param [0] = new EncoderParameter (Encoder.Quality, 95L);

                    var encInfo = GetEncoderInfo ("image/jpeg");
                    if (encInfo != null) {
                        // Save bitmap to stream
                        mapTexture.Save (imgstream, encInfo, myEncoderParameters);
                    } else
                        MainConsole.Instance.Warn ("[Maptile generator]: Unable to save Map image - missing encoder");

                    myEncoderParameters.Dispose ();
                }
            } catch (Exception) {
                // Dummy!
                MainConsole.Instance.Warn ("[Maptile generator]: Unable to generate Map image");
            } finally {
                // Reclaim memory, these are unmanaged resources
                // If we encountered an exception, one or more of these will be null
                if (mapTexture != null)
                    mapTexture.Dispose ();

                if (image != null)
                    image.Dispose ();

                imgstream.Close ();
            }
        }