Example #1
0
	public static void DumpCodeInfo (ImageCodecInfo codec)
	{
		Console.WriteLine ("Clsid:" + codec.Clsid);
		Console.WriteLine ("FormatID:" + codec.FormatID);			
		Console.WriteLine ("Codec:" + codec.CodecName);
		Console.WriteLine ("DllName:" + codec.DllName);
		Console.WriteLine ("Extension:" + codec.FilenameExtension);
		Console.WriteLine ("Format:" + codec.FormatDescription);
		Console.WriteLine ("MimeType:" + codec.MimeType);
		Console.WriteLine ("Flags:" + codec.Flags);			
		Console.WriteLine ("Version:" + codec.Version);			
	}
Example #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Form["width"] != null && Request.Form["width"] != String.Empty)
        {
            // image dimensions
            int width  = Int32.Parse((Request.Form["width"].IndexOf('.') != -1) ? Request.Form["width"].Substring(0, Request.Form["width"].IndexOf('.')) : Request.Form["width"]);
            int height = Int32.Parse((Request.Form["height"].IndexOf('.') != -1) ? Request.Form["height"].Substring(0, Request.Form["height"].IndexOf('.')) : Request.Form["height"]);

            // image
            Bitmap result = new Bitmap(width, height);

            // set pixel colors
            for (int y = 0; y < height; y++)
            {
                // column counter for the row
                int x = 0;
                // get current row data
                string[] row = Request.Form["r" + y].Split(new char[] { ',' });
                // set pixels in the row
                for (int c = 0; c < row.Length; c++)
                {
                    // get pixel color and repeat count
                    string[] pixel         = row[c].Split(new char[] { ':' });
                    Color    current_color = ColorTranslator.FromHtml("#" + pixel[0]);
                    int      repeat        = pixel.Length > 1 ? Int32.Parse(pixel[1]) : 1;

                    // set pixel(s)
                    for (int l = 0; l < repeat; l++)
                    {
                        result.SetPixel(x, y, current_color);
                        x++;
                    }
                }
            }

            // output image

            // image type
            Response.ContentType = "image/jpeg";

            // find image encoder for selected type
            ImageCodecInfo[] encoders;
            ImageCodecInfo   img_encoder = null;
            encoders = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codec in encoders)
            {
                if (codec.MimeType == Response.ContentType)
                {
                    img_encoder = codec;
                    break;
                }
            }

            // image parameters
            EncoderParameter  jpeg_quality = new EncoderParameter(Encoder.Quality, 100L); // for jpeg images only
            EncoderParameters enc_params   = new EncoderParameters(1);
            enc_params.Param[0] = jpeg_quality;

            result.Save(Response.OutputStream, img_encoder, enc_params);
        }
    }
Example #3
0
        public void DoThumbnail(Image image, string outputPath, ref ImageInfo imageInfo)
        {
            int realWidth  = image.Width;
            int realHeight = image.Height;

            imageInfo.OriginalWidth  = realWidth;
            imageInfo.OriginalHeight = realHeight;

            EncoderParameters ep = new EncoderParameters(1);

            ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)90);

            ImageCodecInfo icJPG = getCodecInfo("image/jpeg");

            if (!String.IsNullOrEmpty(imageInfo.Name) && imageInfo.Name.Contains("."))
            {
                int indexDot = imageInfo.Name.ToLower().LastIndexOf(".");

                if (imageInfo.Name.ToLower().IndexOf("png", indexDot) > indexDot)
                {
                    icJPG = getCodecInfo("image/png");
                }
                else if (imageInfo.Name.ToLower().IndexOf("gif", indexDot) > indexDot)
                {
                    icJPG = getCodecInfo("image/png");
                }
            }
            Bitmap thumbnail;

            if (realWidth < _width && realHeight < _heigth)
            {
                imageInfo.ThumbnailWidth  = realWidth;
                imageInfo.ThumbnailHeight = realHeight;

                if (store == null)
                {
                    image.Save(outputPath);
                }
                else
                {
                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, icJPG, ep);
                    ms.Seek(0, SeekOrigin.Begin);
                    store.Save(outputPath, ms);
                    ms.Dispose();
                }
                return;
            }
            else
            {
                thumbnail = new Bitmap(_width < realWidth ? _width : realWidth, _heigth < realHeight ? _heigth : realHeight);

                int maxSide = realWidth > realHeight ? realWidth : realHeight;
                int minSide = realWidth < realHeight ? realWidth : realHeight;

                bool alignWidth = true;
                if (_crop)
                {
                    alignWidth = (minSide == realWidth);
                }
                else
                {
                    alignWidth = (maxSide == realWidth);
                }

                double scaleFactor = (alignWidth) ? (realWidth / (1.0 * _width)) : (realHeight / (1.0 * _heigth));

                if (scaleFactor < 1)
                {
                    scaleFactor = 1;
                }

                int locationX, locationY;
                int finalWidth, finalHeigth;

                finalWidth  = (int)(realWidth / scaleFactor);
                finalHeigth = (int)(realHeight / scaleFactor);


                locationY = (int)(((_heigth < realHeight ? _heigth : realHeight) / 2.0) - (finalHeigth / 2.0));
                locationX = (int)(((_width < realWidth ? _width : realWidth) / 2.0) - (finalWidth / 2.0));

                Rectangle rect = new Rectangle(locationX, locationY, finalWidth, finalHeigth);

                imageInfo.ThumbnailWidth  = thumbnail.Width;
                imageInfo.ThumbnailHeight = thumbnail.Height;


                using (Graphics graphic = Graphics.FromImage(thumbnail))
                {
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    graphic.DrawImage(image, rect);
                }
            }

            if (store == null)
            {
                thumbnail.Save(outputPath, icJPG, ep);
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                thumbnail.Save(ms, icJPG, ep);
                ms.Seek(0, SeekOrigin.Begin);
                store.Save(outputPath, ms);
                ms.Dispose();
            }

            thumbnail.Dispose();
        }
Example #4
0
        /// <summary>
        /// Processes the file
        /// </summary>
        /// <returns></returns>
        public override bool Run()
        {
            //if (image == null)
            System.Drawing.Image image;
            image = (System.Drawing.Image)(new Bitmap(File.FullName, true));

            Log.Debug("  * Bearbetar fil: {0}...", File.Name);

            string new_name = getNewName(File);

            FileInfo nfi = new FileInfo(new_name);

            if (nfi.Exists)
            {
                try { System.IO.File.Delete(nfi.FullName); }
                catch (Exception e) {
                    Log.File("Kunde inte radera gammal kopia:\n    {0}\n", e.Message);
                    Log.File("    Nästa operation kommer förmodligen att misslyckas!\n");
                }
            }

            if (MaxWidth == 0 && MaxHeight == 0)
            {
                if (Attributes != null)
                {
                    Bitmap nimg;
                    using (nimg = Gfx.ApplyAttributes((Bitmap)image, Image.Attributes)) {
                        image.Dispose();
                        image = null;

                        EncoderParameters eparams = new EncoderParameters(1);
                        eparams.Param[0] =
                            new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)95);
                        ImageFormat    fmt;
                        string         mime = GetMimeTypeForExtension(nfi.Extension, out fmt);
                        ImageCodecInfo ici  = Gfx.GetEncoderInfo(mime);

                        try {
                            if (ici != null)
                            {
                                nimg.Save(new_name, ici, eparams);
                            }
                            else
                            {
                                nimg.Save(new_name, fmt);
                            }

                            Log.Debug("klar\n");

                            nimg.Dispose();
                            nimg = null;
                        }
                        catch (Exception e) {
                            Log.File("    misslyckades!\n");
                            Log.File("    fel: {0}\n", e.Message);
                            FileInfo fi = new FileInfo(new_name);
                            if (fi.Exists)
                            {
                                try { System.IO.File.Delete(fi.FullName); }
                                catch { }
                            }

                            nimg.Dispose();
                            nimg = null;
                            return(false);
                        }
                    }
                }
            }
            else
            {
                int[] constraints = Gfx.GetConstraints(image.Width, image.Height,
                                                       MaxWidth, MaxHeight);
                Bitmap nimg;
                using (nimg = Gfx.ScaleImage((Bitmap)image, constraints[0],
                                             constraints[1])) {
                    //image = null;
                    image.Dispose();
                    image = null;

                    if (Image.Attributes != null)
                    {
                        nimg = Gfx.ApplyAttributes(nimg, Image.Attributes);
                    }

                    EncoderParameters eparams = new EncoderParameters(1);
                    eparams.Param[0] =
                        new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)95);
                    ImageFormat    fmt;
                    string         mime = GetMimeTypeForExtension(nfi.Extension, out fmt);
                    ImageCodecInfo ici  = Gfx.GetEncoderInfo(mime);

                    try {
                        if (ici != null)
                        {
                            nimg.Save(new_name, ici, eparams);
                        }
                        else
                        {
                            nimg.Save(new_name, fmt);
                        }

                        Log.Debug("klar\n");

                        nimg.Dispose();
                        nimg = null;
                    }
                    catch (Exception e) {
                        Log.File("    misslyckades!\n");
                        Log.File("    fel: {0}\n", e.Message);
                        FileInfo fi = new FileInfo(new_name);
                        if (fi.Exists)
                        {
                            try { System.IO.File.Delete(fi.FullName); }
                            catch { }
                        }

                        nimg.Dispose();
                        nimg = null;
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #5
0
        /// <summary>
        /// 根据路径 生成 缩略图
        /// </summary>
        /// <param name="p_strSource">传回的图片路径</param>
        /// <param name="p_strSave">图片保存的新路径</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode"></param>
        /// <param name="q">质量</param>
        public static void Thumbnail(string p_strSource, string p_strSave, int width, int height, CutMode mode, long q = 100L)
        {
            FileInfo fileInfo = new FileInfo(p_strSave);

            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            Image image = Image.FromFile(p_strSource);
            int   num   = width;
            int   num2  = height;
            int   x     = 0;
            int   y     = 0;
            int   num3  = image.Width;
            int   num4  = image.Height;

            switch (mode)
            {
            case CutMode.WH:
                break;

            case CutMode.W:
                num2 = image.Height * width / image.Width;
                break;

            case CutMode.H:
                num = image.Width * height / image.Height;
                break;

            case CutMode.Cut:
                if ((double)image.Width / (double)image.Height < (double)num / (double)num2)
                {
                    num4 = image.Height;
                    num3 = image.Height * num / num2;
                    y    = 0;
                    x    = (image.Width - num3) / 2;
                    break;
                }
                num3 = image.Width;
                num4 = image.Width * height / num;
                x    = 0;
                y    = (image.Height - num4) / 2;
                break;

            default:
                if (image.Width > image.Height)
                {
                    num2 = image.Height * width / image.Width;
                }
                else
                {
                    num = image.Width * height / image.Height;
                }
                break;
            }

            Image    image2   = new Bitmap(num, num2);
            Graphics graphics = Graphics.FromImage(image2);

            graphics.InterpolationMode = InterpolationMode.High;
            graphics.SmoothingMode     = SmoothingMode.HighQuality;
            graphics.Clear(Color.White);
            graphics.DrawImage(image, new Rectangle(0, 0, num, num2), new Rectangle(x, y, num3, num4), GraphicsUnit.Pixel);
            try
            {
                ImageCodecInfo    encoderInfo       = IMGUtility.GetEncoderInfo("image/jpeg");
                Encoder           quality           = Encoder.Quality;
                EncoderParameters encoderParameters = new EncoderParameters(1);
                EncoderParameter  encoderParameter  = new EncoderParameter(quality, q);
                encoderParameters.Param[0] = encoderParameter;
                image2.Save(p_strSave, encoderInfo, encoderParameters);
            }
            catch (Exception ex)
            {
                image.Dispose();
                image2.Dispose();
                graphics.Dispose();
                throw ex;
            }
            finally
            {
                image.Dispose();
                image2.Dispose();
                graphics.Dispose();
            }
        }
Example #6
0
        public void CheckUploadedImageAndCreateThumbs(ref string temporaryFile,
                                                      params ImageCheckResult[] supportedFormats)
        {
            if (supportedFormats == null ||
                supportedFormats.Length == 0)
            {
                supportedFormats = new ImageCheckResult[] { ImageCheckResult.JPEGImage, ImageCheckResult.GIFImage, ImageCheckResult.PNGImage }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = this.MinWidth;
            checker.MaxWidth    = this.MaxWidth;
            checker.MinHeight   = this.MinHeight;
            checker.MaxHeight   = this.MaxHeight;
            checker.MaxDataSize = this.MaxBytes;

            Image image = null;

            try
            {
                var temporaryPath = Path.Combine(UploadHelper.TemporaryPath, temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (this.MinBytes != 0 && fs.Length < this.MinBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en az {0} boyutunda olmalı!",
                                                                UploadHelper.FileSizeDisplay(this.MinBytes)));
                    }

                    if (this.MaxBytes != 0 && fs.Length > this.MaxBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en çok {0} boyutunda olabilir!",
                                                                UploadHelper.FileSizeDisplay(this.MaxBytes)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result > ImageCheckResult.FlashMovie ||
                        Array.IndexOf(supportedFormats, result) < 0)
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result != ImageCheckResult.FlashMovie)
                    {
                        string basePath = UploadHelper.TemporaryPath;
                        string baseFile = Path.GetFileNameWithoutExtension(temporaryFile);

                        TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                        if ((this.ScaleWidth > 0 || this.ScaleHeight > 0) &&
                            ((this.ScaleWidth > 0 && (this.ScaleSmaller || checker.Width > this.ScaleWidth)) ||
                             (this.ScaleHeight > 0 && (this.ScaleSmaller || checker.Height > this.ScaleHeight))))
                        {
                            using (Image scaledImage = ThumbnailGenerator.Generate(
                                       image, this.ScaleWidth, this.ScaleHeight, this.ScaleMode, Color.Empty))
                            {
                                temporaryFile = baseFile + ".jpg";
                                fs.Close();
                                scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }

                        var thumbSizes = this.ThumbSizes.TrimToNull();
                        if (thumbSizes != null)
                        {
                            foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                            {
                                var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                                int w, h;
                                if (dims.Length != 2 ||
                                    !Int32.TryParse(dims[0], out w) ||
                                    !Int32.TryParse(dims[1], out h) ||
                                    w < 0 ||
                                    h < 0 ||
                                    (w == 0 && h == 0))
                                {
                                    throw new ArgumentOutOfRangeException("thumbSizes");
                                }

                                using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, this.ThumbMode, Color.Empty))
                                {
                                    string thumbFile = Path.Combine(basePath,
                                                                    baseFile + "t_" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                                    if (this.ThumbQuality != 0)
                                    {
                                        var p = new System.Drawing.Imaging.EncoderParameters(1);
                                        p.Param[0] = new EncoderParameter(Encoder.Quality, 80L);

                                        ImageCodecInfo   jpegCodec = null;
                                        ImageCodecInfo[] codecs    = ImageCodecInfo.GetImageEncoders();
                                        // Find the correct image codec
                                        for (int i = 0; i < codecs.Length; i++)
                                        {
                                            if (codecs[i].MimeType == "image/jpeg")
                                            {
                                                jpegCodec = codecs[i];
                                            }
                                        }
                                        thumbImage.Save(thumbFile, jpegCodec, p);
                                    }
                                    else
                                    {
                                        thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
Example #7
0
 public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
 {
     Image.Save(filename, encoder, encoderParams);
 }
Example #8
0
    /// <summary>

    /// 保存图片

    /// </summary>

    /// <param name="image">Image 对象</param>

    /// <param name="savePath">保存路径</param>

    /// <param name="ici">指定格式的编解码参数</param>

    private void SaveImage(Image image, string savePath, ImageCodecInfo ici)
    {

        //设置 原图片 对象的 EncoderParameters 对象

        var parameters = new EncoderParameters(1);

        parameters.Param[0] = new EncoderParameter(

            Encoder.Quality, ((long)90));

        image.Save(savePath, ici, parameters);

        parameters.Dispose();

    }
Example #9
0
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <remarks>汪磊 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">保存路径</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //释放资源
            initImage.Dispose();
        }
Example #10
0
        public void Say()
        {
            string imgPath = "aaa";
            Image  img     = Image.FromFile(imgPath);
            //新图第一帧
            Image new_img = new Bitmap(100, 100);
            //新图其他帧
            Image new_imgs = new Bitmap(100, 100);
            //新图第一帧GDI+绘图对象
            Graphics g_new_img = Graphics.FromImage(new_img);
            //新图其他帧GDI+绘图对象
            Graphics g_new_imgs = Graphics.FromImage(new_imgs);

            //配置新图第一帧GDI+绘图对象
            g_new_img.CompositingMode   = CompositingMode.SourceCopy;
            g_new_img.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g_new_img.PixelOffsetMode   = PixelOffsetMode.HighQuality;
            g_new_img.SmoothingMode     = SmoothingMode.HighQuality;
            g_new_img.Clear(Color.FromKnownColor(KnownColor.Transparent));
            //配置其他帧GDI+绘图对象
            g_new_imgs.CompositingMode   = CompositingMode.SourceCopy;
            g_new_imgs.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g_new_imgs.PixelOffsetMode   = PixelOffsetMode.HighQuality;
            g_new_imgs.SmoothingMode     = SmoothingMode.HighQuality;
            g_new_imgs.Clear(Color.FromKnownColor(KnownColor.Transparent));
            //遍历维数
            foreach (Guid gid in img.FrameDimensionsList)
            {
                //因为是缩小GIF文件所以这里要设置为Time
                //如果是TIFF这里要设置为PAGE
                FrameDimension f = FrameDimension.Time;
                //获取总帧数
                int count = img.GetFrameCount(f);
                //保存标示参数
                System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
                //
                EncoderParameters ep = null;
                //图片编码、解码器
                ImageCodecInfo ici = null;
                //图片编码、解码器集合
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageDecoders();
                //为 图片编码、解码器 对象 赋值
                foreach (ImageCodecInfo ic in icis)
                {
                    if (ic.FormatID == ImageFormat.Gif.Guid)
                    {
                        ici = ic;
                        break;
                    }
                }
                //每一帧
                for (int c = 0; c < count; c++)
                {
                    //选择由维度和索引指定的帧
                    img.SelectActiveFrame(f, c);
                    //第一帧
                    if (c == 0)
                    {
                        //将原图第一帧画给新图第一帧
                        g_new_img.DrawImage(img, new Rectangle(0, 0, 100, 100), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                        //把振频和透明背景调色板等设置复制给新图第一帧
                        for (int i = 0; i < img.PropertyItems.Length; i++)
                        {
                            new_img.SetPropertyItem(img.PropertyItems[i]);
                        }
                        ep = new EncoderParameters(1);
                        //第一帧需要设置为MultiFrame
                        ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
                        //保存第一帧
                        new_img.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"/temp/" + Path.GetFileName(imgPath), ici, ep);
                    }
                    //其他帧
                    else
                    {
                        //把原图的其他帧画给新图的其他帧
                        g_new_imgs.DrawImage(img, new Rectangle(0, 0, 100, 100), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                        //把振频和透明背景调色板等设置复制给新图第一帧
                        for (int i = 0; i < img.PropertyItems.Length; i++)
                        {
                            new_imgs.SetPropertyItem(img.PropertyItems[i]);
                        }
                        ep = new EncoderParameters(1);
                        //如果是GIF这里设置为FrameDimensionTime
                        //如果为TIFF则设置为FrameDimensionPage
                        ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionTime);
                        //向新图添加一帧
                        new_img.SaveAdd(new_imgs, ep);
                    }
                }
                ep = new EncoderParameters(1);
                //关闭多帧文件流
                ep.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
                new_img.SaveAdd(ep);
            }
        }
 private static string GetMimeType(ImageFormat imageFormat)
 {
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
     return(codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType);
 }
Example #12
0
        public static string SaveBitmap(Bitmap bitmap, string path, string fileName = null, int quality = 100, bool isResize = true)
        {
            int maxWidth = 2000;

            if (isResize && bitmap.Width > maxWidth)
            {
                double height = (int)(bitmap.AspectRatio() * maxWidth);
                bitmap = Resizer.ResizeImage(bitmap, null, maxWidth.ToString(), height.ToString(), FitMode.Max);
            }
            //int maxHeight = 2000;
            //if (isResize)
            //{
            //    //TODO:
            ////bitmap = Resizer.ResizeImage(bitmap, null, Width.ToString(), Height.ToString(), FitMode.Max);
            //}

            string extension = "jpg";



            if (string.IsNullOrWhiteSpace(fileName))
            {
                fileName = CreaDev.Framework.Core.IO.File.GetRandomFileName();
            }

            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
            /**/


            // Get an ImageCodecInfo object that represents the JPEG codec.
            var myImageCodecInfo = GetEncoderInfo("image/jpeg");
            // for the Quality parameter category.
            var myEncoder = Encoder.Quality;
            // EncoderParameter object in the array.
            var myEncoderParameters = new EncoderParameters(1);
            // Save the bitmap as a JPEG file with quality provided.
            var myEncoderParameter = new EncoderParameter(myEncoder, (long)quality);

            myEncoderParameters.Param[0] = myEncoderParameter;
            bitmap.Save(path + fileName + "." + extension, myImageCodecInfo, myEncoderParameters);

            return(fileName + "." + extension);
        }

        public static string SaveBitmapByExtension(Bitmap bitmap, string path, string originalFileName, int quality = 100, bool isResize = true)
        {
            int    maxWidth  = 500;
            string extension = originalFileName.Substring(originalFileName.LastIndexOf('.'));
            String mime      = _mappings[extension];


            if (isResize && bitmap.Width > maxWidth)
            {
                double height = (int)(bitmap.AspectRatio() * maxWidth);
                bitmap = Resizer.ResizeImage(bitmap, null, maxWidth.ToString(), height.ToString(), FitMode.Max);
            }
            //int maxHeight = 2000;
            //if (isResize)
            //{
            //    //TODO:
            ////bitmap = Resizer.ResizeImage(bitmap, null, Width.ToString(), Height.ToString(), FitMode.Max);
            //}



            string fileName = CreaDev.Framework.Core.IO.File.GetRandomFileName();

            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
            /**/


            // Get an ImageCodecInfo object that represents the JPEG codec.
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo(mime);


            // for the Quality parameter category.
            var myEncoder = Encoder.Quality;
            // EncoderParameter object in the array.
            var myEncoderParameters = new EncoderParameters(1);
            // Save the bitmap as a JPEG file with quality provided.
            var myEncoderParameter = new EncoderParameter(myEncoder, (long)quality);

            myEncoderParameters.Param[0] = myEncoderParameter;
            bitmap.Save(path + fileName + extension, myImageCodecInfo, myEncoderParameters);

            return(fileName + extension);
        }
Example #13
0
        public static string SaveBitmapByMimeType(Bitmap bitmap, string path, string mimeType, string originalFileName, int quality = 100, bool isResize = true)
        {
            int    maxWidth  = 2000;
            string extension = originalFileName.Substring(originalFileName.LastIndexOf('.'));

            if (isResize && bitmap.Width > maxWidth)
            {
                double height = (int)(bitmap.AspectRatio() * maxWidth);
                bitmap = Resizer.ResizeImage(bitmap, null, maxWidth.ToString(), height.ToString(), FitMode.Max);
            }
            //int maxHeight = 2000;
            //if (isResize)
            //{
            //    //TODO:
            ////bitmap = Resizer.ResizeImage(bitmap, null, Width.ToString(), Height.ToString(), FitMode.Max);
            //}



            string fileName = CreaDev.Framework.Core.IO.File.GetRandomFileName();

            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
            /**/


            // Get an ImageCodecInfo object that represents the JPEG codec.
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo(mimeType);


            // for the Quality parameter category.
            var myEncoder = Encoder.Quality;
            // EncoderParameter object in the array.
            var myEncoderParameters = new EncoderParameters(1);
            // Save the bitmap as a JPEG file with quality provided.
            var myEncoderParameter = new EncoderParameter(myEncoder, (long)quality);

            myEncoderParameters.Param[0] = myEncoderParameter;
            bitmap.Save(path + fileName + extension, myImageCodecInfo, myEncoderParameters);

            return(fileName + extension);
        }

        public static string SaveImageFromBytes(byte[] bytes, string path, string mimeType, string originalFileName, int quality = 100, bool isResize = true)
        {
            Bitmap       bitmap;
            MemoryStream stream = new MemoryStream();

            stream.Write(bytes, 0, bytes.Length);
            stream.Flush();
            bitmap = new Bitmap(stream);
            int    maxWidth  = 2000;
            string extension = originalFileName.Substring(originalFileName.LastIndexOf('.'));

            if (isResize && bitmap.Width > maxWidth)
            {
                double height = (int)(bitmap.AspectRatio() * maxWidth);
                bitmap = Resizer.ResizeImage(bitmap, null, maxWidth.ToString(), height.ToString(), FitMode.Max);
            }
            //int maxHeight = 2000;
            //if (isResize)
            //{
            //    //TODO:
            ////bitmap = Resizer.ResizeImage(bitmap, null, Width.ToString(), Height.ToString(), FitMode.Max);
            //}



            string fileName = CreaDev.Framework.Core.IO.File.GetRandomFileName();

            if (!path.EndsWith("\\"))
            {
                path = path + "\\";
            }
            /**/


            // Get an ImageCodecInfo object that represents the JPEG codec.
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo(mimeType);


            // for the Quality parameter category.
            var myEncoder = Encoder.Quality;
            // EncoderParameter object in the array.
            var myEncoderParameters = new EncoderParameters(1);
            // Save the bitmap as a JPEG file with quality provided.
            var myEncoderParameter = new EncoderParameter(myEncoder, (long)quality);

            myEncoderParameters.Param[0] = myEncoderParameter;
            bitmap.Save(path + fileName + extension, myImageCodecInfo, myEncoderParameters);

            return(fileName + extension);
        }
Example #14
0
        //This is a direct port for default thumbnails that Voat has used in the past
        public static Stream Resize(Stream input, Size maximumSize, bool forceJpegFormat = false, bool square = true, bool scale = true, bool center = true)
        {
            MemoryStream output = null;

            using (var image = Image.FromStream(input))
            {
                using (var bitmapImage = new Bitmap(image))
                {
                    var destinationSize = new Size(maximumSize.Width, maximumSize.Height);
                    //Sizing
                    Size scaledSize = scale ? Scale(bitmapImage.Size, maximumSize) : maximumSize;
                    //The original image size is our source
                    var sourceRectangle = new Rectangle(0, 0, bitmapImage.Size.Width, bitmapImage.Size.Height);

                    //default destination
                    var destinationRectangle = new Rectangle(0, 0, scaledSize.Width, scaledSize.Height);
                    //centered destination
                    if (square && center)
                    {
                        destinationRectangle = Center(maximumSize, scaledSize);
                    }
                    //allow non-squared output
                    if (!square)
                    {
                        destinationSize = destinationRectangle.Size;
                    }

                    var resized = new Bitmap(destinationSize.Width, destinationSize.Height);

                    using (var graphics = Graphics.FromImage(resized))
                    {
                        graphics.CompositingQuality = CompositingQuality.HighSpeed;
                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        graphics.CompositingMode    = CompositingMode.SourceCopy;

                        //Assuming that if we are forcing jpeg we are creating site thumbnails which uses black bars
                        if (forceJpegFormat)
                        {
                            //Draw black background
                            graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black)), new Rectangle(0, 0, maximumSize.Width, maximumSize.Height));
                        }

                        graphics.DrawImage(bitmapImage, destinationRectangle, sourceRectangle, GraphicsUnit.Pixel);

                        output = new MemoryStream();
                        var qualityParamId    = System.Drawing.Imaging.Encoder.Quality;
                        var encoderParameters = new EncoderParameters(1);
                        encoderParameters.Param[0] = new EncoderParameter(qualityParamId, 100);

                        var codec = ImageCodecInfo.GetImageDecoders().FirstOrDefault(x =>
                                                                                     //Force JPEG
                                                                                     (forceJpegFormat && x.FormatID == ImageFormat.Jpeg.Guid)
                                                                                     //Allow source format
                                                                                     || (!forceJpegFormat && x.FormatID == image.RawFormat.Guid)
                                                                                     );

                        resized.Save(output, codec, encoderParameters);

                        //reset resized stream
                        output.Seek(0, SeekOrigin.Begin);
                    }
                }
            }


            return(output);
        }
Example #15
0
 /// <summary>
 /// Method to get encoder infor for given image format.
 /// </summary>
 /// <param name="format">Image format</param>
 /// <returns>image codec info.</returns>
 private ImageCodecInfo GetEncoderInfo(ImageFormat format)
 {
     return(ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid));
 }
	public void Save(System.IO.Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) {}
Example #17
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <remarks>汪磊 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</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();
            }
        }
Example #18
0
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageEncoders();

            return(codecs.FirstOrDefault(x => x.FormatID == format.Guid));
        }
Example #19
0
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量 1-100</param>
        /// <returns></returns>
        public bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag, bool isscal)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat          tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (isscal)
            {
                if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
                {
                    if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                    {
                        sW = dWidth;
                        sH = (dWidth * tem_size.Height) / tem_size.Width;
                    }
                    else
                    {
                        sH = dHeight;
                        sW = (tem_size.Width * dHeight) / tem_size.Height;
                    }
                }
                else
                {
                    sW = tem_size.Width;
                    sH = tem_size.Height;
                }
            }
            else
            {
                sW = dWidth;
                sH = dHeight;
            }
            Bitmap   ob   = new Bitmap(dWidth, dHeight);
            Graphics g    = Graphics.FromImage(ob);

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

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

            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI    = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
Example #20
0
 public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
 {
     Image.Save(stream, encoder, encoderParams);
 }
Example #21
0
 protected override void SaveDocument(Document doc, Bitmap image, ImageCodecInfo codec, EncoderParameters encoderParameters)
 {
     image.Save(ODFileUtils.CombinePaths(patFolder, doc.FileName), codec, encoderParameters);
 }
Example #22
0
        public static string ParseDOCX(byte[] byteArray, string fileName)
        {
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    memoryStream.Write(byteArray, 0, byteArray.Length);
                    using (WordprocessingDocument wDoc =
                               WordprocessingDocument.Open(memoryStream, true))
                    {
                        int imageCounter = 0;
                        var pageTitle    = fileName;
                        var part         = wDoc.CoreFilePropertiesPart;
                        if (part != null)
                        {
                            pageTitle = (string)part.GetXDocument()
                                        .Descendants(DC.title)
                                        .FirstOrDefault() ?? fileName;
                        }

                        WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
                        {
                            AdditionalCss                       = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
                            PageTitle                           = pageTitle,
                            FabricateCssClasses                 = true,
                            CssClassPrefix                      = "pt-",
                            RestrictToSupportedLanguages        = false,
                            RestrictToSupportedNumberingFormats = false,
                            ImageHandler                        = imageInfo =>
                            {
                                ++imageCounter;
                                string      extension   = imageInfo.ContentType.Split('/')[1].ToLower();
                                ImageFormat imageFormat = null;
                                if (extension == "png")
                                {
                                    imageFormat = ImageFormat.Png;
                                }
                                else if (extension == "gif")
                                {
                                    imageFormat = ImageFormat.Gif;
                                }
                                else if (extension == "bmp")
                                {
                                    imageFormat = ImageFormat.Bmp;
                                }
                                else if (extension == "jpeg")
                                {
                                    imageFormat = ImageFormat.Jpeg;
                                }
                                else if (extension == "tiff")
                                {
                                    extension   = "gif";
                                    imageFormat = ImageFormat.Gif;
                                }
                                else if (extension == "x-wmf")
                                {
                                    extension   = "wmf";
                                    imageFormat = ImageFormat.Wmf;
                                }

                                if (imageFormat == null)
                                {
                                    return(null);
                                }

                                string base64 = null;
                                try
                                {
                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        imageInfo.Bitmap.Save(ms, imageFormat);
                                        var ba = ms.ToArray();
                                        base64 = System.Convert.ToBase64String(ba);
                                    }
                                }
                                catch (System.Runtime.InteropServices.ExternalException)
                                { return(null); }

                                ImageFormat    format = imageInfo.Bitmap.RawFormat;
                                ImageCodecInfo codec  = ImageCodecInfo.GetImageDecoders()
                                                        .First(c => c.FormatID == format.Guid);
                                string mimeType = codec.MimeType;

                                string imageSource =
                                    string.Format("data:{0};base64,{1}", mimeType, base64);

                                XElement img = new XElement(Xhtml.img,
                                                            new XAttribute(NoNamespace.src, imageSource),
                                                            imageInfo.ImgStyleAttribute,
                                                            imageInfo.AltText != null ?
                                                            new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                                return(img);
                            }
                        };

                        XElement htmlElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
                        var      html        = new XDocument(new XDocumentType("html", null, null, null),
                                                             htmlElement);
                        var htmlString = html.ToString(SaveOptions.DisableFormatting);
                        return(htmlString);
                    }
                }
            }
            catch (Exception ex)
            {
                return("The file is either open, please close it or contains corrupt data");
            }
        }
Example #23
0
        /// <summary>
        /// draw a bitmap at the given position;
        /// the current position is moved
        ///
        /// Either Width or WidthPercentage should be unequals 0, but only one should have a value.
        /// Same applies to Height
        /// </summary>
        public override void DrawBitmap(string APath,
                                        float AXPos,
                                        float AYPos,
                                        float AWidth,
                                        float AHeight,
                                        float AWidthPercentage,
                                        float AHeightPercentage)
        {
            if (!System.IO.File.Exists(APath))
            {
                throw new Exception("TGfxPrinter.DrawBitmap: cannot find image file " + APath);
            }

            Bitmap img;

            try
            {
                img = new System.Drawing.Bitmap(APath);
            }
            catch (Exception e)
            {
                TLogging.Log("Problem reading image for printing to PDF: " + APath);
                TLogging.Log(e.ToString());
                throw new Exception("Problem reading image for printing to PDF: " + APath);
            }

            float Height = img.Size.Height;

            if (AHeightPercentage != 0.0f)
            {
                Height = Height * AHeightPercentage;
            }
            else
            {
                Height = AHeight;
            }

            float Width = img.Size.Width;

            if (AHeightPercentage != 0.0f)
            {
                Width = Width * AWidthPercentage;
            }
            else
            {
                Width = AWidth;
            }

// there seem to be too many problems with this on Linux. On Linux, the size of the PDF is quite small anyway
#if DEACTIVATED
            if (false && (Width / img.Size.Width * 100 < 80))
            {
                // we should scale down the picture to make the result pdf smaller
                try
                {
                    Bitmap SmallerImg = new Bitmap(Convert.ToInt32(Width), Convert.ToInt32(Height));
                    using (Graphics g = Graphics.FromImage((Image)SmallerImg))
                    {
                        g.DrawImage(img, 0, 0, Convert.ToInt32(Width), Convert.ToInt32(Height));
                    }

                    // saving as PNG file because I get GDI+ status: InvalidParameter in Mono/XSP when trying to save to jpg
                    string ThumbPath = APath.Replace(Path.GetExtension(APath), "thumb.png");

                    ImageCodecInfo[] codecs        = ImageCodecInfo.GetImageDecoders();
                    ImageCodecInfo   jpegCodecInfo = codecs[0];

                    foreach (ImageCodecInfo codec in codecs)
                    {
                        if (codec.FormatID == ImageFormat.Png.Guid)
                        {
                            jpegCodecInfo = codec;
                        }
                    }

                    EncoderParameters codecParams = new EncoderParameters(1);
                    codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 75);
                    SmallerImg.Save(ThumbPath, jpegCodecInfo, codecParams);
                    SmallerImg.Dispose();
                    img.Dispose();

                    File.Delete(ThumbPath);

                    img = new System.Drawing.Bitmap(ThumbPath);
                }
                catch (Exception)
                {
                }
            }
#endif

            DrawBitmapInternal(img, AXPos, AYPos, Width, Height);

            img.Dispose();
        }
 public ImageFormatHandler()
 {
     availableEncoders = ImageCodecInfo.GetImageEncoders();
     availableDecoders = ImageCodecInfo.GetImageDecoders();
 }
Example #25
0
        /// <summary>
        /// Using barcode value to split multi-page documents.
        /// </summary>
        /// <param name="strInputFolder">the path of folder that documents in</param>
        /// <param name="strOutputFolder">the path of folder that splitted documents saved in</param>
        private void DoSplit(string strInputFolder, string strOutputFolder)
        {
            int      iFileCount = 0;
            int      iSuccCount = 0;
            DateTime dtStart    = DateTime.Now;

            string[] files = Directory.GetFiles(strInputFolder);
            if (files != null)
            {
                foreach (string strFile in files)
                {
                    if (IsImageFile(strFile))
                    {
                        try
                        {
                            iFileCount++;
                            int    iDirectSeparator = strFile.LastIndexOf(Path.DirectorySeparatorChar);
                            string strFileName      = strFile.Substring(iDirectSeparator + 1);
                            tbLog.AppendText(string.Format("\r\nProcessing file {0}\r\n", strFileName));
                            if (!strFileName.EndsWith(".tiff", true, System.Globalization.CultureInfo.CurrentCulture) &&
                                !strFileName.EndsWith(".tif", true, System.Globalization.CultureInfo.CurrentCulture))
                            {
                                tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                continue;
                            }

                            string[] Templates  = barcodeReader.GetAllParameterTemplateNames();
                            bool     bifcontian = false;

                            PublicRuntimeSettings tempParameterSettings = barcodeReader.GetRuntimeSettings();
                            tempParameterSettings.BarcodeFormatIds = formatid;
                            barcodeReader.UpdateRuntimeSettings(tempParameterSettings);

                            TextResult[] barcodes = barcodeReader.DecodeFile(strFile, "");
                            if (barcodes == null || barcodes.Length <= 0)
                            {
                                tbLog.AppendText("There is no barcode on the first page\r\n");
                            }
                            else
                            {
                                List <int>    separators        = new List <int>();
                                List <string> values            = new List <string>();
                                List <string> splittedFileNames = new List <string>();
                                foreach (TextResult result in barcodes)
                                {
                                    if (result.LocalizationResult.PageNumber >= 0)
                                    {
                                        if (!separators.Contains(result.LocalizationResult.PageNumber))
                                        {
                                            separators.Add(result.LocalizationResult.PageNumber);
                                            values.Add(result.BarcodeText);
                                        }
                                    }
                                }

                                string strOutputDir = null;
                                if (strOutputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                                {
                                    strOutputDir = strOutputFolder;
                                }
                                else
                                {
                                    strOutputDir = strOutputFolder + Path.DirectorySeparatorChar;
                                }

                                Image          img         = Image.FromFile(strFile);
                                int            iFrameCount = 1;
                                FrameDimension dimension   = FrameDimension.Page;
                                if (img.FrameDimensionsList != null && img.FrameDimensionsList.Length > 0)
                                {
                                    dimension   = new FrameDimension(img.FrameDimensionsList[0]);
                                    iFrameCount = img.GetFrameCount(dimension);
                                }
                                if (iFrameCount <= 1)
                                {
                                    tbLog.AppendText("It's not a multi-page tiff file\r\n");
                                    continue;
                                }

                                bool bHaveExistFile = false;

                                for (int i = 1; i <= separators.Count; i++)
                                {
                                    int start = separators[i - 1];
                                    int end   = start;
                                    if (i != separators.Count)
                                    {
                                        end = separators[i];
                                    }
                                    else
                                    {
                                        end = iFrameCount;
                                    }

                                    tbLog.AppendText(string.Format("Page: {0}\r\n", separators[i - 1]));
                                    tbLog.AppendText(string.Format("Barcode Value: {0}\r\n", values[i - 1]));

                                    string strOutputFileName = values[i - 1] + ".tiff";
                                    string strOutputFile     = strOutputDir + strOutputFileName;

                                    if (File.Exists(strOutputFile))
                                    {
                                        bHaveExistFile = true;
                                        tbLog.AppendText(string.Format("{0} exists,skip splitting pages({1}-{2}) in {3}\r\n", strOutputFileName, start + 1, end, strFileName));
                                        continue;
                                    }

                                    ImageCodecInfo   tiffCodeInfo = null;
                                    ImageCodecInfo[] codeinfos    = ImageCodecInfo.GetImageDecoders();
                                    foreach (ImageCodecInfo codeinfo in codeinfos)
                                    {
                                        if (codeinfo.FormatID == ImageFormat.Tiff.Guid)
                                        {
                                            tiffCodeInfo = codeinfo;
                                            break;
                                        }
                                    }

                                    System.Drawing.Imaging.EncoderParameters encoderParams = null;
                                    if (end - start == 1)
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(1);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                    }
                                    else
                                    {
                                        encoderParams          = new System.Drawing.Imaging.EncoderParameters(2);
                                        encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)System.Drawing.Imaging.EncoderValue.CompressionLZW);
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame);
                                    }

                                    img.SelectActiveFrame(dimension, start);
                                    img.Save(strOutputFile, tiffCodeInfo, encoderParams);
                                    start++;
                                    if (start < end)
                                    {
                                        encoderParams.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage);
                                        for (int k = start; k < end; k++)
                                        {
                                            img.SelectActiveFrame(dimension, k);
                                            img.SaveAdd(img, encoderParams);
                                        }
                                    }
                                    splittedFileNames.Add(strOutputFileName);
                                }

                                img.Dispose();
                                if (!bHaveExistFile)
                                {
                                    iSuccCount++;
                                }

                                string strFiles = null;
                                if (splittedFileNames.Count > 0)
                                {
                                    strFiles = splittedFileNames[0];
                                    for (int j = 1; j < splittedFileNames.Count; j++)
                                    {
                                        strFiles += "," + splittedFileNames[j];
                                    }
                                }
                                if (strFiles != null)
                                {
                                    tbLog.AppendText(string.Format("Splitted it to multiple files:{0}\r\n", strFiles));
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            tbLog.AppendText(exp.Message + "\r\n");
                        }
                        tbLog.Refresh();
                    }
                }
            }

            tbLog.AppendText("Completed\r\n");
            tbLog.AppendText(string.Format("Files Total: {0} file(s), Success: {1} file(s)\r\n", iFileCount, iSuccCount));
            tbLog.AppendText(string.Format("Total cost time: {0}ms", (int)(DateTime.Now - dtStart).TotalMilliseconds));
        }
Example #26
0
        public byte[] EnforceResize(int width, int height, byte[] photobytes, string PhotoFileName)
        {
            if (photobytes == null)
            {
                return(null);
            }
            using (var ms = new MemoryStream(photobytes))
                using (Bitmap src = new Bitmap(ms))
                {
                    var iH = src.Height;
                    var iW = src.Width;
                    var nH = 0;
                    var nW = 0;


                    if (iH > iW && iH > height)
                    {
                        nH = height;
                        nW = iW * nH / iH;
                    }
                    else if (iW > iH && iW > width)
                    {
                        nW = width;
                        nH = iH * nW / iW;
                    }
                    else
                    {
                        nH = iH;
                        nW = iW;
                    }
                    int newWidth  = nW;
                    int newHeight = nH;

                    using (Bitmap bmp = new Bitmap(newWidth, newHeight))
                    {
                        bmp.SetResolution(src.HorizontalResolution, src.VerticalResolution);
                        using (var graphics = Graphics.FromImage(bmp))
                        {
                            graphics.SmoothingMode      = SmoothingMode.HighQuality;
                            graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                            graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                            #region doubleImageAlgorithm

                            //int sourceWidth = src.Width;
                            //int sourceHeight = src.Height;
                            //int sourceX = 0;
                            //int sourceY = 0;
                            //int destX = 0;
                            //int destY = 0;
                            //float nPercent = 0;
                            //float nPercentW = 0;
                            //float nPercentH = 0;

                            //nPercentW = ((float)width / (float)sourceWidth);
                            //nPercentH = ((float)height / (float)sourceHeight);
                            //if (nPercentH < nPercentW)
                            //{
                            //    nPercent = nPercentH;
                            //    destX = Convert.ToInt16((width -
                            //                  (sourceWidth * nPercent)) / 2);
                            //}
                            //else
                            //{
                            //    nPercent = nPercentW;
                            //    destY = Convert.ToInt16((height -
                            //                  (sourceHeight * nPercent)) / 2);
                            //}
                            //int destWidth = (int)(sourceWidth * nPercent);
                            //int destHeight = (int)(sourceHeight * nPercent);
                            //graphics.DrawImage(src, new Rectangle(destX, destX, width, height), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
                            // graphics.DrawImage(srcImage, new Rectangle(0, 0, srcImage.Width, srcImage.Height));

                            #endregion

                            #region Single ImageAlgorithm


                            //double ratioX = (double)width / (double)sourceWidth;
                            //double ratioY = (double)height / (double)sourceHeight;
                            //double ratio = ratioX < ratioY ? ratioX : ratioY;
                            //int newHeight = Convert.ToInt32(sourceHeight * ratio);
                            //int newWidth = Convert.ToInt32(sourceWidth * ratio);
                            //int posX = Convert.ToInt32((width - (sourceWidth * ratio)) / 2);
                            //int posY = Convert.ToInt32((height - (sourceHeight * ratio)) / 2);


                            //graphics.DrawImage(src, posX, posY, newWidth, newHeight);

                            #endregion

                            #region Normal

                            graphics.DrawImage(src, new Rectangle(0, 0, newWidth, newHeight));

                            #endregion

                            var         memoryStream = new MemoryStream();
                            ImageFormat format       = GetImageFormatForSave(PhotoFileName);

                            ImageCodecInfo jpgEncoder = GetEncoder(GetImageFormatForSave(PhotoFileName));
                            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                            EncoderParameters myEncoderParameters    = new EncoderParameters(1);

                            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 60L);
                            myEncoderParameters.Param[0] = myEncoderParameter;
                            bmp.Save(memoryStream, jpgEncoder, myEncoderParameters);
                            //bmp.Save(memoryStream, format);
                            return(memoryStream.ToArray());
                        }
                    }
                }
        }
Example #27
0
 /// <summary>
 /// get codec info by mime type
 /// </summary>
 /// <param name="mimeType"></param>
 /// <returns></returns>
 public static ImageCodecInfo GetEncoderInfo(string mimeType)
 {
     return(ImageCodecInfo.GetImageEncoders().FirstOrDefault(t => t.MimeType == mimeType));
 }
Example #28
0
        public void DoPreviewImage(Image image, string outputPath, ref ImageInfo imageInfo)
        {
            int realWidth  = image.Width;
            int realHeight = image.Height;

            int heightPreview = realHeight;
            int widthPreview  = realWidth;

            EncoderParameters ep    = new EncoderParameters(1);
            ImageCodecInfo    icJPG = getCodecInfo("image/jpeg");

            ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)90);

            if (realWidth <= _widthPreview && realHeight <= _heightPreview)
            {
                imageInfo.PreviewWidth  = widthPreview;
                imageInfo.PreviewHeight = heightPreview;

                if (store == null)
                {
                    image.Save(outputPath);
                }
                else
                {
                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, icJPG, ep);
                    ms.Seek(0, SeekOrigin.Begin);
                    store.Save(outputPath, ms);
                    ms.Dispose();
                }

                return;
            }
            else if ((double)realHeight / (double)_heightPreview > (double)realWidth / (double)_widthPreview)
            {
                if (heightPreview > _heightPreview)
                {
                    widthPreview  = (int)(realWidth * _heightPreview * 1.0 / realHeight + 0.5);
                    heightPreview = _heightPreview;
                }
            }
            else
            {
                if (widthPreview > _widthPreview)
                {
                    heightPreview = (int)(realHeight * _widthPreview * 1.0 / realWidth + 0.5);
                    widthPreview  = _widthPreview;
                }
            }

            imageInfo.PreviewWidth  = widthPreview;
            imageInfo.PreviewHeight = heightPreview;

            Bitmap preview = new Bitmap(widthPreview, heightPreview);

            using (Graphics graphic = Graphics.FromImage(preview))
            {
                graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                graphic.DrawImage(image, 0, 0, widthPreview, heightPreview);
            }

            if (store == null)
            {
                preview.Save(outputPath, icJPG, ep);
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                preview.Save(ms, icJPG, ep);
                ms.Seek(0, SeekOrigin.Begin);
                store.Save(outputPath, ms);
                ms.Dispose();
            }

            preview.Dispose();
        }
        /// <summary>
        /// Save media to stream.
        /// </summary>
        /// <param name="stream">
        /// A <see cref="IO.Stream"/> which stores the media data.
        /// </param>
        /// <param name="image">
        /// A <see cref="Image"/> holding the data to be stored.
        /// </param>
        /// <param name="format">
        /// A <see cref="String"/> that specify the media format to used for saving <paramref name="image"/>.
        /// </param>
        /// <param name="criteria">
        /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an image stream.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Exception thrown if <paramref name="stream"/>, <paramref name="image"/> or <paramref name="criteria"/> is null.
        /// </exception>
        public void Save(Stream stream, Image image, string format, ImageCodecCriteria criteria)
        {
            System.Drawing.Imaging.ImageFormat bitmapFormat;
            System.Drawing.Imaging.PixelFormat bitmapPixelFormat;
            int iBitmapFlags;

            ConvertImageFormat(format, out bitmapFormat);
            ConvertPixelFormat(image.PixelLayout, out bitmapPixelFormat, out iBitmapFlags);

            // Obtain source and destination data pointers
            using (Bitmap bitmap = new Bitmap((int)image.Width, (int)image.Height, bitmapPixelFormat)) {
                #region Copy Image To Bitmap

                BitmapData iBitmapData = null;
                IntPtr     imageData   = image.ImageBuffer;

                try {
                    iBitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);

                    // Copy Image data dst Bitmap
                    unsafe {
                        byte *hImageDataPtr     = (byte *)imageData.ToPointer();
                        byte *iBitmapDataPtr    = (byte *)iBitmapData.Scan0.ToPointer();
                        uint  hImageDataStride  = image.Stride;
                        uint  iBitmapDataStride = (uint)iBitmapData.Stride;

                        // .NET Image Library stores bitmap scan line data in memory padded dst 4 bytes boundaries
                        // .NET Image Library expect a bottom up image, so invert the scan line order

                        iBitmapDataPtr = iBitmapDataPtr + ((image.Height - 1) * iBitmapDataStride);

                        for (uint line = 0; line < image.Height; line++, hImageDataPtr += hImageDataStride, iBitmapDataPtr -= iBitmapDataStride)
                        {
                            Memory.MemoryCopy(iBitmapDataPtr, hImageDataPtr, hImageDataStride);
                        }
                    }
                } finally {
                    if (iBitmapData != null)
                    {
                        bitmap.UnlockBits(iBitmapData);
                    }
                }

                #endregion

                #region Support Indexed Pixel Formats

                if ((iBitmapFlags & (int)ImageFlags.ColorSpaceGray) != 0)
                {
                    ColorPalette bitmapPalette = bitmap.Palette;

                    switch (bitmapPixelFormat)
                    {
                    case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                        // Create grayscale palette
                        for (int i = 0; i <= 255; i++)
                        {
                            bitmapPalette.Entries[i] = Color.FromArgb(i, i, i);
                        }
                        break;
                    }

                    bitmap.Palette = bitmapPalette;
                }

                #endregion

                // Save image with the specified format
                ImageCodecInfo encoderInfo = Array.Find(ImageCodecInfo.GetImageEncoders(), delegate(ImageCodecInfo item) {
                    return(item.FormatID == bitmapFormat.Guid);
                });

                EncoderParameters encoderParams = null;

                try {
                    EncoderParameters  encoderInfoParamList = bitmap.GetEncoderParameterList(encoderInfo.Clsid);
                    EncoderParameter[] encoderInfoParams    = encoderInfoParamList != null ? encoderInfoParamList.Param : null;
                    bool supportQuality = false;
                    int  paramsCount    = 0;

                    if (encoderInfoParams != null)
                    {
                        Array.ForEach(encoderInfoParams, delegate(EncoderParameter item) {
                            if (item.Encoder.Guid == Encoder.Quality.Guid)
                            {
                                supportQuality = true;
                                paramsCount++;
                            }
                        });
                    }

                    encoderParams = new EncoderParameters(paramsCount);

                    paramsCount = 0;
                    if (supportQuality)
                    {
                        encoderParams.Param[paramsCount++] = new EncoderParameter(Encoder.Quality, 100);
                    }
                } catch (Exception) {
                    // Encoder does not support parameters
                }

                bitmap.Save(stream, encoderInfo, encoderParams);
            }
        }
Example #30
0
        public Image GetEntireScreenshotMobile(AndroidDriver <AndroidElement> _driver, string deviceUDID)
        {
            // Get the total size of the page
            var totalWidth =
                (int)(long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.offsetWidth"); //documentElement.scrollWidth");
            var totalHeight = (int)(long)((IJavaScriptExecutor)_driver).ExecuteScript("return  document.body.parentNode.scrollHeight");
            // Get the size of the viewport
            var viewportWidth  = (int)(long)((IJavaScriptExecutor)_driver).ExecuteScript("return document.body.clientWidth"); //documentElement.scrollWidth");
            var viewportHeight = (int)(long)((IJavaScriptExecutor)_driver).ExecuteScript("return window.innerHeight");        //documentElement.scrollWidth");

            // We only care about taking multiple images together if it doesn't already fit
            if (totalWidth <= viewportWidth && totalHeight <= viewportHeight)
            {
                var screenshot = _driver.TakeScreenshot();
                return(ScreenshotToImage(screenshot));
            }
            // Split the screen in multiple Rectangles
            var rectangles = new List <Rectangle>();

            // Loop until the totalHeight is reached
            for (var y = 0; y < totalHeight; y += viewportHeight)
            {
                var newHeight = viewportHeight;
                // Fix if the height of the element is too big
                if (y + viewportHeight > totalHeight)
                {
                    newHeight = totalHeight - y;
                }
                // Loop until the totalWidth is reached
                for (var x = 0; x < totalWidth; x += viewportWidth)
                {
                    var newWidth = viewportWidth;
                    // Fix if the Width of the Element is too big
                    if (x + viewportWidth > totalWidth)
                    {
                        newWidth = totalWidth - x;
                    }
                    // Create and add the Rectangle
                    var currRect = new Rectangle(x, y, newWidth, newHeight);
                    rectangles.Add(currRect);
                }
            }
            // Build the Image
            var stitchedImage = new Bitmap(totalWidth, totalHeight);
            // Get all Screenshots and stitch them together
            var previous = Rectangle.Empty;

            foreach (var rectangle in rectangles)
            {
                // Calculate the scrolling (if needed)
                if (previous != Rectangle.Empty)
                {
                    var xDiff = rectangle.Right - previous.Right;
                    var yDiff = rectangle.Bottom - previous.Bottom;

                    // Take Screenshot
                    var screenshotB = _driver.TakeScreenshot();
                    // Build an Image out of the Screenshot
                    var screenshotImageB = ScreenshotToImage(screenshotB);
                    pathSCR = _hndlr.PathProject() + "ANDROIDSCR\\" + deviceUDID + DateTime.Now.ToString("MMdHHmmss") + ".jpg";
                    _pathBitmapPreMade.Add(pathSCR);
                    var encoder   = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);
                    var encParams = new EncoderParameters()
                    {
                        Param = new[] { new EncoderParameter(Encoder.Quality, 75L) }
                    };
                    screenshotImageB.Save(pathSCR, encoder, encParams);
                    // Scroll
                    ((IJavaScriptExecutor)_driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff));
                    System.Threading.Thread.Sleep(200);
                }
                // Take Screenshot
                var screenshot = _driver.TakeScreenshot();
                // Build an Image out of the Screenshot
                var screenshotImage = ScreenshotToImage(screenshot);
                // Calculate the source Rectangle
                var sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height);
                // Copy the Image
                using (var graphics = Graphics.FromImage(stitchedImage))
                {
                    graphics.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel);
                }
                // Set the Previous Rectangle
                previous = rectangle;
            }
            return(Collage(_pathBitmapPreMade));
        }
Example #31
0
 private static ImageCodecInfo GetEncoder(ImageFormat format)
 {
     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
     return(codecs.Single(codec => codec.FormatID == format.Guid));
 }
	public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams) {}
Example #33
0
        /// <summary>
        /// 文字水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="fontname">字体</param>
        /// <param name="fontsize">字体大小</param>
        public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = Utils.GetMapPath(filename);

            Graphics g = Graphics.FromImage(img);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode   = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Font  drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF crSize;

            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

            qualityParam[0] = quality;

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

            encoderParams.Param[0] = encoderParam;

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

            g.Dispose();
            img.Dispose();
        }
Example #34
0
 //Icon2TileRendering iconizer;
 public void Init()
 {
     _codecInfo = GetEncoderInfo("image/png");
     _bitmap = GetInitialTile();
     DetectFormat();
 }
Example #35
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(Utils.GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = Utils.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode   = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            Image watermark = new Bitmap(watermarkFilename);

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

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

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

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

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


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

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

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

            int xpos = 0;
            int ypos = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

            qualityParam[0] = quality;

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

            encoderParams.Param[0] = encoderParam;

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

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }