Example #1
1
        public static Image EnsureMaximumDimensions(Image image, int maxWidth, int maxHeight)
        {
            // Prevent using images internal thumbnail
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);

            var aspectRatio = ((double)image.Width) / image.Height; //AR = L/A;

            int imageWidth = image.Width;
            int imageHeight = image.Height;

            if (imageWidth > maxWidth)
            {
                imageWidth = maxWidth;
                imageHeight = (int)(imageWidth / aspectRatio);
            }
            if (imageHeight > maxHeight)
            {
                imageHeight = maxHeight;
                imageWidth = (int)(imageHeight * aspectRatio);
            }

            if (image.Width != imageWidth || image.Height != imageHeight)
                return image.GetThumbnailImage(imageWidth, imageHeight, null, IntPtr.Zero);

            return image;
        }
Example #2
0
 /// <summary>
 /// 生成缩略图,返回缩略图的Image对象
 /// </summary>
 /// <param name="Width">缩略图宽度</param>
 /// <param name="Height">缩略图高度</param>
 /// <returns>缩略图的Image对象</returns>
 public System.Drawing.Image GetImage(int Width, int Height)
 {
     System.Drawing.Image img;
     System.Drawing.Image.GetThumbnailImageAbort callb = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
     img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
     return(img);
 }
        public Bitmap ResizeBitmap(Bitmap bitmap, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
        {
            int newheigth = heigth;

            System.Drawing.Image FullsizeImage = bitmap;
            if (keepAspectRatio || getCenter)
            {
                int    bmpY   = 0;
                double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
                if (getCenter)
                {
                    bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);                                                 // gives the Y value of the part that will be cut off, to show only the part in the center
                    Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize))); // create the section to cut of the original image
                                                                                                                                  //System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY);
                    Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);                                                             //for the correct effect convert image to bitmap.
                    FullsizeImage.Dispose();                                                                                      //clear the original image
                    using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                    {
                        Graphics cutImg = Graphics.FromImage(tempImg);              //              set the file to save the new image to.
                        cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel); // cut the image and save it to tempImg
                        FullsizeImage = tempImg;                                    //save the tempImg as FullsizeImage for resizing later
                        orImg.Dispose();
                        cutImg.Dispose();
                        return(new Bitmap(FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero)));
                    }
                }
                else
                {
                    newheigth = (int)(FullsizeImage.Height / resize); //  set the new heigth of the current image
                }
            }//return the image resized to the given heigth and width
            return(new Bitmap(FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero)));
        }
Example #4
0
 private System.Drawing.Image NewThumbnailMainImage(System.Drawing.Image image)
 {
     System.Drawing.Image thumb = image.GetThumbnailImage(image.Width, image.Height, () => false, IntPtr.Zero);
     if (image.Width < 1000 || image.Height < 1000)
     {
         thumb = image.GetThumbnailImage(image.Width, image.Height, () => false, IntPtr.Zero);
     }
     else
     {
         thumb = image.GetThumbnailImage(image.Width / 2, image.Height / 2, () => false, IntPtr.Zero);
     }
     return(thumb);
 }
Example #5
0
        public static System.Drawing.Image resizeImage(this System.Drawing.Image image, int?width, int?height)
        {
            if (height == null && width != null)
            {
                height = (image.Height * width) / image.Width;
            }
            if (height == null && width == null)
            {
                return(image.GetThumbnailImage(0, 0, () => false, IntPtr.Zero));
            }

            return(image.GetThumbnailImage(width.Value, height.Value, null, IntPtr.Zero));
        }
        private Image GetThumbnil(HttpPostedFile image)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(image.InputStream);
            Image thumb = img.GetThumbnailImage(120, 120, () => false, IntPtr.Zero);

            return(thumb);
        }
Example #7
0
        public byte[] GetThumbnailImage(byte[] contentBytes, int width, int height)
        {
            if (contentBytes == null)
            {
                return(null);
            }

            MemoryStream stream = new MemoryStream(contentBytes);

            System.Drawing.Image image        = null;
            System.Drawing.Image systhumbnail = null;

            image = System.Drawing.Image.FromStream(stream);

            if (image.Width < width && image.Height < height)
            {
                return(contentBytes);
            }

            systhumbnail = image.GetThumbnailImage(width, height, null, new IntPtr());

            MemoryStream memstream = new MemoryStream();

            systhumbnail.Save(memstream, image.RawFormat);
            return(memstream.ToArray());
        }
Example #8
0
        private void ConvertToImages(IPresentation presentation, string filename)
        {
            int i = 1;

            imageList.Clear();
            List <Image> Values   = new List <Image>(4);
            string       name     = null;
            string       itemPath = "../images/presentation/";

            foreach (ISlide slide in presentation.Slides)
            {
                //Converts slide to image
                System.Drawing.Image image = System.Drawing.Image.FromStream(slide.ConvertToImage(Syncfusion.Drawing.ImageFormat.Emf));
                System.Drawing.Image.GetThumbnailImageAbort myCallback =
                    new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image newImage = image.GetThumbnailImage(690, 400, myCallback, System.IntPtr.Zero);
                name = Path.GetFileNameWithoutExtension(filename);
                string dataPath = string.Format("{0}\\Images\\presentation\\", Request.PhysicalPath.ToLower().Split(new string[] { "\\web" }, StringSplitOptions.None));
                string fileName = Path.GetFullPath(dataPath) + name;
                Directory.CreateDirectory(fileName);
                fileName = fileName + "\\" + name + i + ".jpg";
                newImage.Save(fileName);

                imageList.Add(itemPath + name + "/" + name + i + ".jpg");
                //Saves the image
                i += 1;
            }
        }
    // methode used to crope image as Image
    //public static Image CropImageFile(Image imgPhoto, int targetW, int targetH, int targetX, int targetY)
    //{
    //    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
    //    bmPhoto.SetResolution(72, 72);
    //    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    //    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
    //    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
    //    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
    //    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
    //    // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
    //    MemoryStream NewImageStream = new MemoryStream();
    //    bmPhoto.Save(NewImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    //    //Image ReturnImage = Image.FromStream(new MemoryStream(NewImageStream));
    //  //  bmPhoto.sava(imgPhoto, System.Drawing.Imaging.ImageFormat.Jpeg);
    //    imgPhoto.Dispose();
    //    bmPhoto.Dispose();
    //    grPhoto.Dispose();
    //    //returning the Croped image as byte stream
    //    //return ReturnImage;
    //}



    #endregion


    #region "GetThumbNail"
    //byte stream
    public static byte[] GetThumbNail(byte[] ImageStream, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
    {
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(new MemoryStream(ImageStream));

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (OnlyResizeIfWider)
        {
            if (FullsizeImage.Width <= NewWidth)
            {
                NewWidth = FullsizeImage.Width;
            }
        }

        int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

        if (NewHeight > MaxHeight)
        {
            // Resize with height instead
            NewWidth  = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
            NewHeight = MaxHeight;
        }

        System.Drawing.Image ThumbNail      = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
        MemoryStream         NewImageStream = new MemoryStream();

        ThumbNail.Save(NewImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        // Clear handle to original file so that we can overwrite it if necessary
        FullsizeImage.Dispose();
        ThumbNail.Dispose();
        return(NewImageStream.GetBuffer());
    }
    //Image stream

    public static System.Drawing.Image  GetThumbNail(System.Drawing.Image FullsizeImage, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
    {
        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (OnlyResizeIfWider)
        {
            if (FullsizeImage.Width <= NewWidth)
            {
                NewWidth = FullsizeImage.Width;
            }
        }

        int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

        if (NewHeight > MaxHeight)
        {
            // Resize with height instead
            NewWidth  = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
            NewHeight = MaxHeight;
        }

        System.Drawing.Image ThumbNail = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

        // Clear handle to original file so that we can overwrite it if necessary
        FullsizeImage.Dispose();
        return(ThumbNail);
    }
Example #11
0
        private Image GetPreview(System.Drawing.Image scan)
        {
            int desiredHeight;
            int desiredWidht;

            if (scan.Height <= scan.Width)
            {
                desiredWidht  = PreviewSize;
                desiredHeight = (int)(PreviewSize / 1.41M);
            }
            else
            {
                desiredHeight = PreviewSize;
                desiredWidht  = (int)(PreviewSize / 1.41M);
            }


            try
            {
                return(scan.GetThumbnailImage(desiredWidht, desiredHeight, null, IntPtr.Zero));
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error while generating scan preview: " + e.Message);
                return(null);
            }
        }
        protected void CreateImageFileWithBarcode(string scriptsHTML, string fileName, string code)
        {
            try
            {
                System.Drawing.PointF point      = new System.Drawing.PointF(0, 0);
                System.Drawing.PointF _subPpoint = new System.Drawing.PointF(0, 0);
                System.Drawing.Image  _image     = System.Drawing.Image.FromFile(Server.MapPath("../Gallery/Contents/ticket.PNG"));

                _image = _image.GetThumbnailImage(755, 415, null, IntPtr.Zero);
                HtmlRender.RenderToImage(_image, scriptsHTML, point);

                System.Drawing.Image _barcode = CodeGenerator.CreateBarCode(code);
                //System.Drawing.Image _barcode = Code.CreateQrCode(code, 200);
                //_barcode = _barcode.GetThumbnailImage(150, 150, null, IntPtr.Zero);
                _barcode = _barcode.GetThumbnailImage(200, 70, null, IntPtr.Zero);

                HtmlRender.RenderToImage(_barcode, string.Empty, _subPpoint);
                _barcode.RotateFlip(RotateFlipType.Rotate270FlipX);


                Bitmap bitmap = new Bitmap(755, 415);
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.DrawImage(_image, 0, 0);
                    graphics.DrawImage(_barcode, 630, 115);
                    //graphics.DrawImage(_barcode, 550, 150);
                    bitmap.Save(Server.MapPath("../Gallery/Ticket/" + fileName + ".PNG"), System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            catch (Exception ex)
            {
                string a = ex.Message;
            }
        }
Example #13
0
 /// <summary>
 /// 将tif文件转换成jpg
 /// </summary>
 /// <param name="inPath"></param>
 /// <returns></returns>
 public static string TifToJpg(string inPath)
 {
     if (inPath.Substring(inPath.LastIndexOf('.') + 1).ToLower().IndexOf("jpg") > -1)
     {
         return(inPath);
     }
     if (File.Exists(inPath))
     {
         string fileName1            = inPath;
         string fileName2            = inPath.Substring(0, inPath.LastIndexOf('.')) + ".jpg";
         System.IO.FileStream stream = System.IO.File.OpenRead(fileName1);
         Bitmap bmp = new Bitmap(stream);
         System.Drawing.Image image = bmp;//得到原图
         //创建指定大小的图
         System.Drawing.Image newImage = image.GetThumbnailImage(bmp.Width, bmp.Height, null, new IntPtr());
         Graphics             g        = Graphics.FromImage(newImage);
         g.DrawImage(newImage, 0, 0, newImage.Width, newImage.Height); //将原图画到指定的图上
         g.Dispose();
         stream.Close();
         newImage.Save(fileName2, System.Drawing.Imaging.ImageFormat.Jpeg);
         g.Dispose();
         newImage.Dispose();
         return(fileName2);
     }
     else
     {
         return(null);
     }
 }
Example #14
0
        /// <summary>
        /// Thumb images. Default W = 100;
        /// </summary>
        /// <param name="fullPath"></param>
        /// <param name="virtualPath"></param>
        /// <param name="fileName"></param>
        /// <param name="tbwidth"></param>
        /// <param name="tbheight"></param>
        /// <param name="autoSize"></param>
        /// <returns></returns>
        public static string thumbImg(string fullPath, string virtualPath, string fileName, int tbwidth = 0, int tbheight = 0, bool autoSize = true)
        {
            int width  = 0;
            int height = 0;

            // Thumb image
            System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath + fileName);
            Size thumbSize             = Utility.GetThumbSize(image, 100);

            if (autoSize)
            {
                width  = thumbSize.Width;
                height = thumbSize.Height;
            }
            else
            {
                width  = tbwidth;
                height = tbheight;
            }
            System.Drawing.Image thumb = image.GetThumbnailImage(width, height, null, IntPtr.Zero);
            var thumbPath = System.IO.Path.Combine(virtualPath, "thumb_" + width + "_" + fileName);
            var savePath  = System.IO.Path.Combine(fullPath, "thumb_" + width + "_" + fileName);

            thumb.Save(savePath);
            thumb.Dispose();
            image.Dispose();
            // End thumb
            return(thumbPath);
        }
Example #15
0
        //Image resizing
        public System.Drawing.Image ResizeImg(int maxWidth, int maxHeight, System.Drawing.Image Image)
        {
            int width  = Image.Width;
            int height = Image.Height;

            if (width > maxWidth || height > maxHeight)
            {
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
                float ratio = 0;
                if (width > height)
                {
                    ratio  = (float)width / (float)height;
                    width  = maxWidth;
                    height = Convert.ToInt32(Math.Round((float)width / ratio));
                }
                else
                {
                    ratio  = (float)height / (float)width;
                    height = maxHeight;
                    width  = Convert.ToInt32(Math.Round((float)height / ratio));
                }
                //return the resized image
                return(Image.GetThumbnailImage(width, height, null, IntPtr.Zero));
            }
            //return the original resized image
            return(Image);
        }
Example #16
0
    private System.Drawing.Image ResizeImage(System.Drawing.Image image, int sizeHeight, int sizeWidth)
    {
        int iNewSize = sizeHeight < sizeWidth ? sizeWidth : sizeHeight;

        float fScale;
        float fsHeight = (float)image.Height;
        float fsWidth  = (float)image.Width;

        if (fsWidth > fsHeight)
        {
            float fiNewSize = (float)iNewSize;
            fScale = fiNewSize / fsWidth;
        }
        else
        {
            float fiNewSize = (float)iNewSize;
            fScale = fiNewSize / fsHeight;
        }

        float iNWidth  = fScale * fsWidth;
        float iNHeight = fScale * fsHeight;

        System.Drawing.Size newBmpSize = new System.Drawing.Size((int)iNWidth, (int)iNHeight);

        return(image.GetThumbnailImage(newBmpSize.Width, newBmpSize.Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero));
    }
Example #17
0
        //Image resizing
        public static System.Drawing.Image ResizeImage(int maxWidth, int maxHeight, System.Drawing.Image Image)
        {
            int width  = Image.Width;
            int height = Image.Height;

            if (width > maxWidth || height > maxHeight)
            {
                //The flips are in here to prevent any embedded image thumbnails -- usually from cameras
                //from displaying as the thumbnail image later, in other words, we want a clean
                //resize, not a grainy one.
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);

                float ratio = 0;
                if (width > height)
                {
                    ratio  = (float)width / (float)height;
                    width  = maxWidth;
                    height = Convert.ToInt32(Math.Round((float)width / ratio));
                }
                else
                {
                    ratio  = (float)height / (float)width;
                    height = maxHeight;
                    width  = Convert.ToInt32(Math.Round((float)height / ratio));
                }

                //return the resized image
                return(Image.GetThumbnailImage(width, height, null, IntPtr.Zero));
            }


            //return the original resized image
            return(Image);
        }
 public static System.Drawing.Image Olcekle(string resimYolu, int wid, int hei)
 {
     System.Drawing.Image imgOrg         = System.Drawing.Image.FromFile(resimYolu);
     System.Drawing.Image imgOlceklenmis = imgOrg.GetThumbnailImage(wid, hei, null, IntPtr.Zero);
     imgOrg.Dispose();
     return(imgOlceklenmis);
 }
Example #19
0
        public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth  = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            // Save resized picture
            NewImage.Save(NewFile);
        }
Example #20
0
        } // end of color

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

            //。。。。。。。。。。。
            System.Drawing.Image  thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            System.Drawing.Bitmap bm             = new System.Drawing.Bitmap(thumbnailImage);
            //处理JPG质量的函数
            System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
            if (ici != null)
            {
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                bm.Save(newImagePath, ici, ep);
                //释放所有资源,不释放,可能会出错误。
                ep.Dispose();
                ep = null;
            }
            ici = null;
            bm.Dispose();
            bm = null;
            thumbnailImage.Dispose();
            thumbnailImage = null;
            oldImage.Dispose();
            oldImage = null;
        }
Example #21
0
        public static void FitImageToForm(string originalFile, string newFileAddress, int frameWidth, int frameHeight)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(originalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            int newWidth, newHeight;

            if (FullsizeImage.Height < FullsizeImage.Width)
            {
                newHeight = frameHeight;
                newWidth  = FullsizeImage.Width * Convert.ToInt32((float)newHeight / (float)FullsizeImage.Height);
            }
            else
            {
                newWidth  = frameWidth;
                newHeight = FullsizeImage.Height * Convert.ToInt32((float)newWidth / (float)FullsizeImage.Width);
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();
            // Save resized picture
            NewImage.Save(newFileAddress);
        }
Example #22
0
        public static void smallimage(string imagename, string imgurl, string saveurl, int imgwidth, int imgheight)
        {
            if (imgurl != "")
            {
                //取得图片类型
                string imageType = imgurl.Substring(imgurl.LastIndexOf(".") + 1);
                //取得图片名称
                string imageName = imgurl.Substring(imgurl.LastIndexOf("\\") + 1);
                if (imageType != "jpg" && imageType != "gif" && imageType != "png" && imageType != "bmp")
                {
                    return;
                }

                System.Drawing.Image image = System.Drawing.Image.FromFile(imgurl);

                System.Drawing.Image.GetThumbnailImageAbort callb = null;

                if (imgheight == 0)
                {
                    //使用固定宽度进行等比缩放
                }
                else
                {
                    //按指定的宽度和高度存储图片
                    System.Drawing.Image newimage = image.GetThumbnailImage(imgwidth, imgheight, callb, new System.IntPtr());

                    newimage.Save(saveurl + imagename);
                    newimage.Dispose();
                }
                image.Dispose();
            }
        }
        public void ResizeImage(string origFileLocation, string newFileLocation, string origFileName, string newFileName, int newWidth, int maxHeight, bool resizeIfWider)
        {
            System.Drawing.Image FullSizeImage = System.Drawing.Image.FromFile(origFileLocation + origFileName);
            // Ensure the generated thumbnail is not being used by rotating it 360 degrees
            FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (resizeIfWider)
            {
                if (FullSizeImage.Width <= newWidth)
                {
                    //newWidth = FullSizeImage.Width;
                }
            }

            int newHeight = FullSizeImage.Height * newWidth / FullSizeImage.Width;

            if (newHeight > maxHeight)     // Height resize if necessary
            {
                //newWidth = FullSizeImage.Width * maxHeight / FullSizeImage.Height;
                newHeight = maxHeight;
            }
            newHeight = maxHeight;
            // Create the new image with the sizes we've calculated
            System.Drawing.Image NewImage = FullSizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
            FullSizeImage.Dispose();
            NewImage.Save(newFileLocation + newFileName);
        }
Example #24
0
        public void GetThumbnail(int cx, out IntPtr hBitmap, out WTS_ALPHATYPE bitmapType)
        {
            hBitmap    = IntPtr.Zero;
            bitmapType = WTS_ALPHATYPE.WTSAT_UNKNOWN;

            try
            {
                using (System.Drawing.Image image = System.Drawing.Image.FromStream(GetStreamContents()))
                {
                    int width, height;
                    if (image.Width > image.Height)
                    {
                        width  = cx;
                        height = image.Height * cx / image.Width;
                    }
                    else
                    {
                        height = cx;
                        width  = image.Width * cx / image.Height;
                    }

                    using (Image thumb = image.GetThumbnailImage(width, height, abortCallback, IntPtr.Zero))
                    {
                        using (Bitmap bmp = new Bitmap(thumb))
                        {
                            hBitmap = bmp.GetHbitmap(Color.White);
                        }
                    }
                }
            }
            catch { } // A dirty cop-out.
        }
Example #25
0
        public static Image ScaleImage(Image ImageToScale, double ScaledToHeight, double ScaleToWidth)
        {
            //Hold the min value. Is it the height or the width - Figure out which is the minimum value...the width or the height. Keeps the ratio
            double ScalingValue = Math.Min((ScaleToWidth / ImageToScale.Width), (ScaledToHeight / ImageToScale.Height));

            //Set the final scaled width
            double ScaledWidth = (ScalingValue * ImageToScale.Width);

            //Set the final scaled height
            double ScaledHeight = (ScalingValue * ImageToScale.Height);

            //set the callback to the private method - ThumbnailCallback
            //just use a lamda since the method doesn't do anything
            Image.GetThumbnailImageAbort CallBackForConversion = new Image.GetThumbnailImageAbort(() =>
            {
                try
                {
                    return false;
                }
                catch (Exception)
                {
                    throw;
                }
            });

            //return the image that is going to be scaled
            return ImageToScale.GetThumbnailImage(Convert.ToInt32(ScaledWidth), Convert.ToInt32(ScaledHeight), CallBackForConversion, IntPtr.Zero);
        }
        /// <summary>
        /// Redimensiona imagem
        /// scrPath = path da imagem original
        /// destPath = path para a nova imagem
        /// caso o destPath seja igual ao scrPath, a nova imagem substitui a anterior
        /// </summary>

        public static bool Resize(string srcPath, string destPath, int nWidth, int nHeight)
        {
            bool   retorno = false;
            string temp;

            try
            {
                // abre arquivo original
                System.Drawing.Image img = System.Drawing.Image.FromFile(srcPath);

                int oWidth  = img.Width;  // largura original
                int oHeight = img.Height; // altura original

                // redimensiona se necessario
                if (oWidth > nWidth || oHeight > nHeight)
                {
                    if (oWidth > oHeight)
                    {
                        // imagem horizontal
                        nHeight = (oHeight * nWidth) / oWidth;
                    }
                    else
                    {
                        // imagem vertical
                        nWidth = (oWidth * nHeight) / oHeight;
                    }
                }

                // cria a copia da imagem
                System.Drawing.Image imgThumb = img.GetThumbnailImage(nWidth, nHeight, null, new System.IntPtr(0));

                if (srcPath == destPath)
                {
                    temp = destPath + ".tmp";
                    imgThumb.Save(temp, ImageFormat.Jpeg);
                    img.Dispose();
                    imgThumb.Dispose();

                    File.Delete(srcPath);     // deleta arquivo original
                    File.Copy(temp, srcPath); // copia a nova imagem
                    File.Delete(temp);        // deleta temporário
                }
                else
                {
                    imgThumb.Save(destPath, ImageFormat.Jpeg); // salva nova imagem no destino
                    imgThumb.Dispose();                        // libera memoria
                    img.Dispose();                             // libera memória
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
                retorno = false;
            }
            finally {
                retorno = true;
            }

            return(retorno);
        }
Example #27
0
 public static byte[] CreateThumbnailByteArray(byte[] imageData, int lnWidth, int lnHeight)
 {
     using (MemoryStream inStream = new MemoryStream())
     {
         inStream.Write(imageData, 0, imageData.Length);
         using (System.Drawing.Image image = Bitmap.FromStream(inStream))
         {
             //do not make image bigger
             if (image.Width < lnWidth || image.Height < lnHeight)
             {
                 //if no shrinking is ocurring, return the original bytes
                 return(imageData);
             }
             else
             {
                 using (System.Drawing.Image thumb = image.GetThumbnailImage(lnWidth, lnHeight, null, IntPtr.Zero))
                 {
                     using (MemoryStream outStream = new MemoryStream())
                     {
                         thumb.Save(outStream, System.Drawing.Imaging.ImageFormat.Png);
                         return(outStream.ToArray());
                     }
                 }
             }
         }
     }
 }
Example #28
0
        public void CombineQRCode(string contents, PictureBox qrimage, string codeType, string codeColor,
                                  string erroCorrectionLevel)
        {
            Bitmap bitmap = GenerateQRCode(contents, qrimage, codeType, codeColor, erroCorrectionLevel, false);

            if (bitmap == null)
            {
                return;
            }

            OpenFileDialog openImage = new OpenFileDialog();

            openImage.Title            = "Open a logo image";
            openImage.Filter           = @"jpeg|*.jpg|bmp|*.bmp|gif|*.gif|png|*.png";
            openImage.RestoreDirectory = true;
            openImage.ShowHelp         = true;

            if (openImage.ShowDialog() == DialogResult.OK)
            {
                System.Drawing.Image logo = System.Drawing.Image.FromFile(openImage.FileName);
                logo = logo.GetThumbnailImage(logo.Width / 3, logo.Height / 3, null, IntPtr.Zero);

                int left = (bitmap.Width / 2) - (logo.Width / 2);
                int top  = (bitmap.Height / 2) - (logo.Height / 2);

                Graphics bindedImg = Graphics.FromImage(bitmap);
                bindedImg.DrawImage(logo, new Point(left, top));

                qrimage.Image = bitmap;
            }
        }
Example #29
0
        static void TestStream()
        {
            const string IMAGE_FILE   = @"test.jpg";
            const string THUMB_STREAM = "thumb";

            //List all of the alternative streams for the file:
            NTFS.FileStreams FS = new NTFS.FileStreams(IMAGE_FILE);
            Console.WriteLine(FS.FileName);
            foreach (NTFS.StreamInfo s in FS)
            {
                Console.WriteLine("\t" + s.Name);
            }


            //Using an alternative stream to store a thumbnail image:
            System.Drawing.Image thm;
            System.IO.FileStream FileStream;

            int i = FS.IndexOf(THUMB_STREAM);

            if (i == -1)
            {
                //Thumbnail stream not found - create and store the thumbnail:
                Console.WriteLine("Creating thumbnail:");
                System.Drawing.Image img = System.Drawing.Image.FromFile(IMAGE_FILE);
                int Width = 100; int Height = 100;

                //Maintain aspect ratio:
                int lW = (int)(img.Width * Height / img.Height);
                int lH = (int)(img.Height * Width / img.Width);
                if (lW > Width)
                {
                    Height = lH;
                }
                else if (lH > Height)
                {
                    Width = lW;
                }
                thm = img.GetThumbnailImage(Width, Height, null, IntPtr.Zero);

                //Save the thumbnail to the stream
                FS.Add(THUMB_STREAM);
                FileStream = FS[THUMB_STREAM].Open(System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                thm.Save(FileStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                FileStream.Close();
                Console.WriteLine("Created thumbnail: Size {0}x{1}", thm.Width, thm.Height);
            }
            else
            {
                //Thumbnail stream exists - read the thumbnail back
                Console.WriteLine("Thumbnail already exists!");
                FileStream = FS[THUMB_STREAM].Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
                thm        = System.Drawing.Image.FromStream(FileStream);
                FileStream.Close();
                Console.WriteLine("Read thumbnail: Size {0}x{1}", thm.Width, thm.Height);

                //Remove the thumbnail stream, for demo purposes only!
                FS.Remove(THUMB_STREAM);
            }
        }
        protected void CreateCertificate(string scriptsHTML, string fileName)
        {
            System.Drawing.PointF point      = new System.Drawing.PointF(-50, 50);
            System.Drawing.PointF _subPpoint = new System.Drawing.PointF(0, 0);
            System.Drawing.Image  _image     = System.Drawing.Image.FromFile(Server.MapPath("../Gallery/Contents/certificate.PNG"));

            //Before here define text as image
            _image = _image.GetThumbnailImage(5000, 3533, null, IntPtr.Zero);
            HtmlRender.RenderToImage(_image, scriptsHTML, point);

            //System.Drawing.Image _barcode = CodeGenerator.CreateBarCode(fileName);
            System.Drawing.Image _barcode = Code.CreateQrCode(fileName, 445);
            _barcode = _barcode.GetThumbnailImage(425, 425, null, IntPtr.Zero);
            //_barcode = _barcode.GetThumbnailImage(200, 70, null, IntPtr.Zero);

            HtmlRender.RenderToImage(_barcode, string.Empty, _subPpoint);
            //_barcode.RotateFlip(RotateFlipType.Rotate270FlipX);

            Bitmap bitmap = new Bitmap(5000, 3533);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(_image, 0, 0);
                graphics.DrawImage(_barcode, 4350, 2900);
                bitmap.Save(Server.MapPath("../Gallery/Certificate/" + fileName + ".PNG"), System.Drawing.Imaging.ImageFormat.Png);
            }
        }
        // <summary>
        // Adds a file to the output dir by creating a thumbnail and directories
        // that represent the year and month the picture was taken from.
        // </summary>
        // <param name="path"> The path of the file to be transfered. </param>
        // <param name="result"> The result of the operation. </param>
        // <returns> Path to transfer the file if succedded, otherwise a failure message. </returns>
        public string AddFile(string path, out bool result)
        {
            if (!Directory.Exists(m_OutputFolder))
            {
                DirectoryInfo createdDir = Directory.CreateDirectory(m_OutputFolder);
                //makes the directory hidden
                createdDir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }
            else
            {
                DirectoryInfo dirExist = new DirectoryInfo(m_OutputFolder);
                //if not hidden, will hide the folder
                if (!dirExist.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    dirExist.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
                }
            }
            if (!IsPathValid(path))
            {
                result = false;
                return("path not valid");
            }

            try
            {
                Thread.Sleep(1000);
                //moving file to the correct dir
                string   imageName      = Path.GetFileName(path);
                DateTime imageDateTime  = GetDateTakenFromImage(path);
                string   pathToTransfer = m_OutputFolder + "\\" + imageDateTime.Year + "\\" + imageDateTime.Month;
                Directory.CreateDirectory(pathToTransfer);
                if (File.Exists(pathToTransfer + "\\" + Path.GetFileName(path)))
                {
                    File.Delete(pathToTransfer + "\\" + Path.GetFileName(path));
                }
                File.Move(path, pathToTransfer + "\\" + Path.GetFileName(path));

                //creating thumnail
                Directory.CreateDirectory(this.m_OutputFolder + "\\thumbnails\\" + imageDateTime.Year + "\\" + imageDateTime.Month);
                string pathToTransferThumb = m_OutputFolder + "\\thumbnails\\" + imageDateTime.Year + "\\" + imageDateTime.Month + "\\" + imageName;
                System.Drawing.Image image = System.Drawing.Image.FromFile(pathToTransfer + "\\" + imageName);
                System.Drawing.Image thumb = image.GetThumbnailImage(this.m_thumbnailSize, this.m_thumbnailSize, () => false, IntPtr.Zero);
                if (File.Exists(pathToTransferThumb))
                {
                    File.Delete(pathToTransferThumb);
                }
                thumb.Save(pathToTransferThumb);

                //success
                result = true;
                return(pathToTransfer);
            }
            catch (Exception e)
            {
                //no success
                result = false;
                return("could not transfer file " + Path.GetFileName(path) + " - " + e.Message + "\n" + e.StackTrace);
            }
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fupImage.HasFile)
            {
                string[] validFileTypes = { "zip" };
                string   ext            = Path.GetExtension(fupImage.PostedFile.FileName);
                bool     isValidFile    = false;
                for (int i = 0; i < validFileTypes.Length; i++)
                {
                    if (ext == "." + validFileTypes[i])
                    {
                        isValidFile = true;
                        break;
                    }
                }
                if (!isValidFile)
                {
                    lblMsg.ForeColor = Color.Red;
                    lblMsg.Text      = "Invalid File. Please upload a File with extension " +
                                       string.Join(",", validFileTypes);
                }
                else
                {
                    string uploadedFile = Utilities.FormateFileName(Path.GetFileNameWithoutExtension(fupImage.PostedFile.FileName)) + Path.GetExtension(fupImage.PostedFile.FileName);
                    string location     = Server.MapPath("~/ZipFiles/" + uploadedFile);
                    fupImage.SaveAs(location);

                    ZipFile fileToExtract = ZipFile.Read(location);

                    // Check subcategory folder is exist or not. If not then create folder and extract image there.
                    // After that create thumb image from regular image.
                    var extractImagePath = Server.MapPath("~/Images/" + ddlSub.SelectedValue.Trim() + "/");
                    if (!Directory.Exists(extractImagePath))
                    {
                        Directory.CreateDirectory(extractImagePath);
                        Directory.CreateDirectory(extractImagePath + "/Thumb/");
                    }
                    fileToExtract.ExtractAll(extractImagePath, ExtractExistingFileAction.DoNotOverwrite);

                    foreach (var item in fileToExtract)
                    {
                        // Load image.
                        System.Drawing.Image image = System.Drawing.Image.FromFile(extractImagePath + item.FileName);

                        // Compute thumbnail size.
                        Size thumbnailSize = Utilities.GetThumbnailSize(image);

                        // Get thumbnail.
                        System.Drawing.Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height, null, IntPtr.Zero);

                        // Save thumbnail.
                        thumbnail.Save(extractImagePath + "/Thumb/" + item.FileName);
                    }

                    lblMsg.ForeColor = Color.Green;
                    lblMsg.Text      = "Image(s) uploaded successfully.";
                }
            }
        }
 public void newPBox_Click(object sender, EventArgs e)
 {
     string newIcon = ((PictureBox)sender).Tag.ToString();
       workingImage = Image.FromFile(newIcon);
       pbCurrentIcon.Image = workingImage.GetThumbnailImage(128, 128, null, new IntPtr());
       workingImage.Dispose();
       buttonTexture = newIcon;
 }
Example #34
0
        public Image GetThumbNail( Image image, int new_width, int new_height )
        {
            Image.GetThumbnailImageAbort thumbnailCallback = new Image.GetThumbnailImageAbort( DummyThumbnailCallback );

            Image thumbnail = image.GetThumbnailImage( new_width, new_height, thumbnailCallback, IntPtr.Zero );

            return thumbnail;
        }
        /// <summary>
        ///     Gets a thumbnail image that represents the specified <paramref name="image"/>.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="width">The thumbnail image width.</param>
        /// <param name="height">The thumbnail image height.</param>
        /// <returns>The thumbnail image.</returns>
        public static Image GetThumbnail(Image image, int width, int height)
        {
            Check.Require<ArgumentNullException>(image != null, "image");
            Check.Require<ArgumentOutOfRangeException>(width > 0, "width");
            Check.Require<ArgumentOutOfRangeException>(height > 0, "height");

            return image.GetThumbnailImage(
                width,
                height,
                () => false,
                IntPtr.Zero);
        }
Example #36
0
        /// <summary>
        /// create a thumbnail from the original image
        /// </summary>
        /// <param name="originalImage">the original image from which the thumbnail is created</param>
        /// <param name="imageHeight">the height of the thumbnail</param>
        /// <returns></returns>
        public static Image CreateThumbnail(Image originalImage, int imageHeight)
        {
            // create thumbnail
            float ratio = (float)originalImage.Width / originalImage.Height;
            int imageWidth = (int)(imageHeight * ratio);

            // set the thumbnail image
            Image thumbnailImage = originalImage.GetThumbnailImage(imageWidth, imageHeight,
                new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

            return thumbnailImage;
        }
Example #37
0
        public void UpdateImage(Image image, float thumbnailCoef)
        {
            int deltHeight = this.Height - this.pictureBox1.Height;
            int deltWidth = this.Width - this.pictureBox1.Width;

            Size thumbnailSize = new Size((int)(image.Width * thumbnailCoef), (int)(image.Height * thumbnailCoef));
            this.Size = new Size(thumbnailSize.Width + deltWidth, thumbnailSize.Height + deltHeight);                       
            
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack);

            Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height, myCallBack, IntPtr.Zero);//生成缩略图
            this.pictureBox1.Image = thumbnail;   
        }
Example #38
0
        public static Image Scale(Image img, int maxWidth, int maxHeight, double scale)
        {
            if (img.Width > maxWidth || img.Height > maxHeight)
            {
                double scaleW, scaleH;

                scaleW = maxWidth / (double)img.Width;
                scaleH = maxHeight / (double)img.Height;

                scale = scaleW < scaleH ? scaleW : scaleH;
            }

            return img.GetThumbnailImage((int)(img.Width * scale), (int)(img.Height * scale), null, IntPtr.Zero);
        }
        /// <summary>
        /// Creates a thumbnail from the image provided, scaled down to the
        /// new height specified while keeping the aspect ratio
        /// </summary>
        /// <param name="fullImage">The image to replicate</param>
        /// <param name="newHeight">The new height to scale to</param>
        /// <returns>Returns a thumbnail Image</returns>
        public Image CreateThumbnail(Image fullImage, int newHeight)
        {
            Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            int newWidth;
            if (fullImage.Height > fullImage.Width)
            {
                newWidth = Convert.ToInt32(Math.Round((double) ((fullImage.Height/fullImage.Width)*newHeight)));
            }
            else
            {
                newWidth = Convert.ToInt32(Math.Round((double) ((fullImage.Width/fullImage.Height)*newHeight)));
            }

            return fullImage.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);
        }
Example #40
0
        public Negative(Image image, int width = 0, int height = 0)
        {
            if (width != height)
            {
                double ratio = width >= height ? (double)image.Height / image.Width : (double)image.Width / image.Height;
                if (width == 0)
                    width = (int)(height * ratio);
                if (height == 0)
                    height = (int)(width * ratio);
            }

            if (width == 0 && height == 0)
                _image = image;
            else _image = image.GetThumbnailImage(width, height, null, IntPtr.Zero);
        }
 void populateScreen(string theme)
 {
     iconFiles.Clear();
       flThemeButtons.Controls.Clear();
       themePreview.Image = Image.FromFile(Path.Combine(Path.Combine(streamedMPMediaPath, "homebuttons"), theme + "themepreview.jpg"));
       iconList(theme);
       foreach (string icon in iconFiles)
       {
     PictureBox newPBox = new PictureBox();
     newPBox.Size = new Size(64, 64);
     workingImage = Image.FromFile(icon);
     newPBox.Image = workingImage.GetThumbnailImage(64, 64, null, new IntPtr());
     workingImage.Dispose();
     flThemeButtons.Controls.Add(newPBox);
       }
 }
Example #42
0
        public Image ResizeImage( Image fullsizeImage, int newWidth )
        {
            // Prevent using images internal thumbnail
            fullsizeImage.RotateFlip( System.Drawing.RotateFlipType.Rotate180FlipNone );
            fullsizeImage.RotateFlip( System.Drawing.RotateFlipType.Rotate180FlipNone );

            var newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width;
            
            var newImage = fullsizeImage.GetThumbnailImage( newWidth, newHeight, null, IntPtr.Zero );

            // Clear handle to original file so that we can overwrite it if necessary
            fullsizeImage.Dispose();

            // Save resized picture
            return newImage;
        }
Example #43
0
 public static Image LowQualityScaledThumbnail(Image iImage,
     Int32 iMaxWidth,
     Int32 iMaxHeight)
 {
     Double pDblRatio = 0;
     if (iImage.Width > iImage.Height)
     {
         pDblRatio = (Double)iMaxWidth / iImage.Width;
     }
     else
     {
         pDblRatio = (Double)iMaxHeight / iImage.Height;
     }
     Double pDblRescaledWidth = iImage.Width * pDblRatio;
     Double pDblRescaledHeight = iImage.Height * pDblRatio;
     return (iImage.GetThumbnailImage((Int32)pDblRescaledWidth, (Int32)pDblRescaledHeight, null, IntPtr.Zero));
 }
        private void LoadImage(Image image)
        {
            this.CalculateTextSize();
            _szText.Height += 4;
            this.Height += _szText.Height + GAP_SIZE_SHADOW;
            this.Width += GAP_SIZE_SHADOW;

            Rectangle rc = this.ClientRectangle;
            _rcClient = new Rectangle(rc.Left + GAP_OFFSET_SHADOW, rc.Top + GAP_OFFSET_SHADOW,
                                      rc.Width - GAP_SIZE_SHADOW, rc.Height - GAP_SIZE_SHADOW);

            using (image)
            {
                _imageThumbnail = image.GetThumbnailImage(_rcClient.Width - GAP_SIZE,
                                                        _rcClient.Height - _szText.Height - GAP_SIZE,
                                                        null, IntPtr.Zero);
            }
        }
Example #45
0
        internal void ResizeImage(Image source, Stream stream)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            Size size = DetermineScalingSize(source, _widthThreshold, _heightThreshold);

            ImageConverter imageConverter = new ImageConverter();

            using (Image resized = source.GetThumbnailImage(size.Width, size.Height, () => false, IntPtr.Zero))
            {
                ImageCodecInfo jpgEncoder = GetEncoderInfo("image/jpeg");
                using (EncoderParameters encoderParameters = GetEncodeParamaters(_compression))
                {
                    resized.Save(stream, jpgEncoder, encoderParameters);
                }
            }
        }
Example #46
0
        public static Image ResizeImage(Image imgToResize, Rectangle maxOffset)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = (float)maxOffset.Width / sourceWidth;
            nPercentH = (float)maxOffset.Height / sourceHeight;

            nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            return imgToResize.GetThumbnailImage(destWidth, destHeight, null, IntPtr.Zero);
        }
        private static Printscreen Capture(Image img, string process)
        {
            Printscreen printscreen = new Printscreen();
            switch (Options.Type)
            {
                case Options.ImageType.PNG:
                    img.Save(printscreen.filePath, ImageFormat.Png);
                    break;
                case Options.ImageType.JPEG:
                    SaveJPEG(printscreen.filePath, img);
                    break;
            }

            printscreen.Resolution = string.Format("{0}x{1}", img.Width, img.Height);
            printscreen.Size = BytesToString(new FileInfo(printscreen.filePath).Length);
            printscreen.Thumb = img.GetThumbnailImage(200, 112, null, IntPtr.Zero);
            printscreen.Process = process;
            printscreen.Save();
            return printscreen;
        }
Example #48
0
        public static Image ResizeImage(Image image, int width, int height, bool onlyResizeIfWider)
        {
            // Prevent using images internal thumbnail
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);
            image.RotateFlip(RotateFlipType.Rotate180FlipNone);

            if (onlyResizeIfWider)
                if (image.Width <= width)
                    width = image.Width;

            var newHeight = image.Height * width / image.Width;
            if (newHeight > height)
            {
                // Resize with height instead
                width = image.Width * height / image.Height;
                newHeight = height;
            }

            return image.GetThumbnailImage(width, newHeight, null, IntPtr.Zero);
        }
Example #49
0
        public static MemoryStream GetMemoryStream2(Image input, int width, int height, ImageFormat fmt)
        {

            // Chargement de l'image
            //Image img = Image.FromFile(@"D:\Jaymz\Images\Pochettes\DVD\" + leFilm.Jaquette);
            // Resalisation de la miniature en 100x100
            // maintain aspect ratio 
            if (input.Width > input.Height)
                height = input.Height * width / input.Width;
            else
                width = input.Width * height / input.Height;
            
            input = input.GetThumbnailImage(width, height, null, IntPtr.Zero);
            // Envoie de l'image au client
            MemoryStream ms = new MemoryStream();

            input.Save(ms, fmt);
            ms.Position = 0;
            return ms;
        }
Example #50
0
        public static Image GetReducedImage(Image ResourceImage,int outWidth,int outHeight,double percent)
        {
            try
            {
                int orgWidth = ResourceImage.Width;
                int orgHeight = ResourceImage.Height;
                int newHeight, newWidth, Top, Left;
                double fscale =(double)orgWidth /(double)orgHeight;
                if ((double)orgWidth * fscale > orgHeight)
                {
                    //图片比较宽
                    newWidth = outWidth;
                    Left = 0;
                    newHeight = (int)((double)orgHeight * ((double)outWidth/(double)orgWidth));
                    Top = (outHeight / 2) - (newHeight / 2);

                }
                else
                {
                    //图片比较长
                    newHeight = outHeight;
                    Top = 0;
                    newWidth =(int)((double)orgWidth * ( (double)outHeight/(double)orgHeight));
                    Left = (outWidth / 2) - (newWidth / 2);
                }

                Top = Top < 0 ? 0 : Top;
                Left = Left < 0 ? 0 : Left;
                Image ReducedImage;
                ReducedImage = ResourceImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
                Bitmap bitmap = new Bitmap(outWidth, outHeight, PixelFormat.Format32bppArgb);
                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.FillRectangle(new SolidBrush(Color.WhiteSmoke), new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                graphics.DrawImage(ReducedImage, new Rectangle(Left, Top, newWidth, newHeight));
                return ReducedImage;
            }
            catch (Exception)
            {
                return null;
            }
        }
Example #51
0
        //Добавляем в коллекцию
        public bool Add(Image img, string key)
        {
            if (mColl.ContainsKey(key) && img!=null)
                return false;
            //добавляем в коллекцию иконок и узнаем индекс иконки
            int index=-1;
            if (img.Width==mIList.ImageSize.Width)
            {

                index=mIList.Images.AddStrip(img);
                mColl.Add(key, index);
            }
            else
            {
                Image img2=img.GetThumbnailImage(mIList.ImageSize.Height,mIList.ImageSize.Width,null,IntPtr.Zero);
                index=mIList.Images.Count;
                mIList.Images.Add(img2);
                mColl.Add(key, index);
            }
            return true;
        }
        private static Image PerformResize(int newWidth, int maxHeight, bool onlyResizeIfWider, Image fullsizeImage)
        {
            if (onlyResizeIfWider)
            {
                if (fullsizeImage.Width <= newWidth)
                    newWidth = fullsizeImage.Width;
            }

            int widthRatio = newWidth/fullsizeImage.Width;
            int newHeight = fullsizeImage.Height*widthRatio;

            if (newHeight > maxHeight)
            {
                // Resize with height instead
                int heightRatio = maxHeight/fullsizeImage.Height;
                newWidth = fullsizeImage.Width*heightRatio;
                newHeight = maxHeight;
            }

            Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
            return newImage;
        }
Example #53
0
        /*public static Image AppendBorder(Image original, int borderWidth)
        {
            var borderColor = Color.White;

            var newSize = new Size(
                original.Width + borderWidth * 2,
                original.Height + borderWidth * 2);

            var img = new Bitmap(newSize.Width, newSize.Height);
            var g = Graphics.FromImage(img);

            g.Clear(borderColor);
            g.DrawImage(original, new Point(borderWidth, borderWidth));
            g.Dispose();

            return img;
        }*/

        //Image resizing
        public static System.Drawing.Image ResizeImage(Image Image, int maxWidth, int maxHeight)
        {
            //return FixedSize(Image, maxWidth, maxHeight, true);
            int width = Image.Width;
            int height = Image.Height;
            if (width > maxWidth || height > maxHeight)
            {
                //The flips are in here to prevent any embedded image thumbnails -- usually from cameras
                //from displaying as the thumbnail image later, in other words, we want a clean
                //resize, not a grainy one.
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);
                Image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipX);

                float ratio = 0;
                if (width > height)
                {
                    ratio = (float)width / (float)height;
                    width = maxWidth;
                    height = Convert.ToInt32(Math.Round((float)width / ratio));
                }
                else
                {
                    ratio = (float)height / (float)width;
                    height = maxHeight;
                    width = Convert.ToInt32(Math.Round((float)height / ratio));
                }

                //Rectangle destRect = new Rectangle(0, 0, maxWidth, maxHeight);
                //// Draw image to screen.
                //e.Graphics.DrawImage(newImage, destRect);

                //return the resized image
                return Image.GetThumbnailImage(width, height, null, IntPtr.Zero);
            }
            //return the original resized image
            return Image;
        }
        private bool ResizeToMax(ref Image inImage, int MaxWidth, int MaxHeight)
        {
            bool resized = false;
            if (inImage.Width > MaxWidth || inImage.Height > MaxHeight)
            {
                int finalWidth = Math.Min(inImage.Width, MaxWidth);

                int finalHeight = inImage.Height * finalWidth / inImage.Width;
                if (finalHeight > MaxHeight)
                {
                    finalWidth = inImage.Width * MaxHeight / inImage.Height;
                    finalHeight = MaxHeight;
                }

                resized = true;
                inImage = inImage.GetThumbnailImage(finalWidth, finalHeight, null, IntPtr.Zero);
            }
            return resized;
        }
Example #55
0
        private void AddIcon(string name, Image img)
        {
            if (img.Width > 256 || img.Height > 256) {
                var widthIsConstraining = img.Width > img.Height;
                // Prevent using images internal thumbnail
                img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                var newWidth = widthIsConstraining ? 256 : img.Width*256/img.Height;
                var newHeight = widthIsConstraining ? img.Height*256/img.Width : 256;
                var newImage = img.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
                img.Dispose();
                img = newImage;
            }

            var tmpImage = (name + ".png").GetFileInTempFolder();
            img.Save(tmpImage, ImageFormat.Png);
            var icon = wix.Product.Add("Binary");

            icon.Attributes.Id = "ICON_{0}".format(name);
            icon.Attributes.SourceFile = tmpImage;
        }
        public static Image ResizeImage(Image FullsizeImage, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            return FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
        }
Example #57
0
 /// <summary>
 /// Set the alpha channel of the current image from the given <paramref name="greyscale"/>.
 /// </summary>
 /// <param name="greyscale"><see cref="Image"/> to use to set alpha channel.</param>
 public void SetAlphaFromGreyscale(Image greyscale)
 {
     try
     {
         base.Enabled = false;
         Application.UseWaitCursor = true;
         Application.DoEvents();
         if (greyscale.Width != image.Width || greyscale.Height != image.Height)
             greyscale = greyscale.GetThumbnailImage(image.Width, image.Height, () => false, System.IntPtr.Zero);
         ddsFile.SetAlphaFromGreyscale(greyscale);
     }
     finally { base.Enabled = true; Application.UseWaitCursor = false; Application.DoEvents(); }
     ckb_CheckedChanged(null, null);
 }
Example #58
0
        void NewFace(Image face, Image markup, Image antiFace)
        {
            if (this.InvokeRequired)
            {
                //BeginInvoke(new Action<Image, Image, Image>(NewFace)(face, markup, antiFace));
                Action<Image,Image,Image> del = new Action<Image,Image,Image>(NewFace);
                BeginInvoke(del, face, markup, antiFace);
                return;
            }
            if (face != null) {
                double adj = 400.0/(double) face.Width;
                pictureBox2.Image = face.GetThumbnailImage((int)(face.Width * adj), (int)(face.Height * adj), null, IntPtr.Zero);
            }
            if (markup != null)
            {
                // we'll keep the height the same, and change the picture box width as needed to accomodate the aspect ratio.
                double aspectRatio = (double) markup.Height / (double) markup.Width;
                pictureBox1.Width = (int) (pictureBox1.Height / aspectRatio);
                pictureBox1.Image = (Image)
                    (new Bitmap(markup, new Size(pictureBox1.Width, pictureBox1.Height)));

                // may need to re-center if we've changed the aspect ratio.
                resizeDebuggingWindow();
            }
            if (antiFace != null)
            {
                double adj = 400.0 / (double)antiFace.Width;
                pictureBox3.Image = antiFace.GetThumbnailImage((int)(antiFace.Width * adj), (int)(antiFace.Height * adj), null, IntPtr.Zero);
            }
            //Console.WriteLine("Done screen update " + DateTime.Now.ToLongTimeString());
            //System.Threading.Thread.Sleep(100);
        }
 /// <summary>
 /// Create a Thumbnail
 /// </summary>
 /// <param name="image">Image of which we need a Thumbnail</param>
 /// <returns>Image with Thumbnail</returns>
 public Image GetThumbnail(Image image, int width, int height)
 {
     return image.GetThumbnailImage(width, height,  new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
 }
Example #60
0
		/// <summary>
		/// Put an image in the PictureBox, sized to 200 x 198
		/// </summary>
		void setImage(Image img) {
			Despatch(delegate() {
				pictureBox1.Image = img == null ? null : img.GetThumbnailImage(200, 198, delegate() { return false; }, new IntPtr());
			});
		}