Dispose() public method

public Dispose ( ) : void
return void
    private void UploadFile()
    {
        if (iFileUpload.HasFile)
        {
            string Address = "~\\Administrator\\files\\Design\\" + FileName;
            string str     = "";
            str = Server.MapPath(Address);

            iFileUpload.PostedFile.SaveAs(str);


            string s = Server.MapPath("~\\Administrator\\files\\Design\\Default\\" + FileName);
            string d = Server.MapPath("~\\Administrator\\files\\Design\\" + FileName);

            System.Drawing.Image oimg = System.Drawing.Image.FromFile(s);
            System.Drawing.Image nimg = System.Drawing.Image.FromFile(d);

            if (oimg.Size == nimg.Size)
            {
                lbErr.Visible = false;
            }
            else
            {
                nimg.Dispose();
                oimg.Dispose();
                LinkButton1_Click(null, null);
                lbErr.Visible = true;
            }

            nimg.Dispose();
            oimg.Dispose();
        }
    }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <param name="image">The current image to process</param>
        /// <param name="newImage">The new Image to return</param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image TransformImage(ImageFactory factory, Image image, Image newImage)
        {
            using (Graphics graphics = Graphics.FromImage(newImage))
            {
                using (ImageAttributes attributes = new ImageAttributes())
                {
                    attributes.SetColorMatrix(this.Matrix);

                    Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height);

                    graphics.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
                }
            }

            // Add a vignette to finish the effect.
            factory.Update(newImage);
            Vignette vignette = new Vignette();
            newImage = (Bitmap)vignette.ProcessImage(factory);

            // Reassign the image.
            image.Dispose();
            image = newImage;

            return image;
        }
Beispiel #3
0
    public byte[] ResizeSmallImage(FileUpload Fup, int widthPerc, int HeightPerc)
    {
        MemoryStream ms = new MemoryStream((byte[])Fup.FileBytes);

        System.Drawing.Image Original = System.Drawing.Image.FromStream(ms);



        int height = Original.Height;
        int width  = Original.Width;

        if (width <= 150)
        {
            widthPerc = width;
        }
        if (height <= 100)
        {
            HeightPerc = height;
        }
        System.Drawing.Bitmap   newPic = new System.Drawing.Bitmap(widthPerc, HeightPerc);
        System.Drawing.Graphics gr     = System.Drawing.Graphics.FromImage(newPic);
        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gr.DrawImage(Original, 0, 0, widthPerc, HeightPerc);
        MemoryStream ms1 = new MemoryStream();

        newPic.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
        gr.Dispose();
        newPic.Dispose();
        Original.Dispose();
        return(ms1.ToArray());
    }
Beispiel #4
0
 public static Image Crop(Image originalImage, RectangleF rect)
 {
     Bitmap bmpImage = new Bitmap(originalImage);
     Bitmap bmpCrop = bmpImage.Clone(rect, bmpImage.PixelFormat);
     originalImage.Dispose();
     return (Image)(bmpCrop);
 }
        public int[][] ParseImage(Image pic)
        {
            Bitmap bitmapPic = new Bitmap(this.MATRIX_WIDTH, this.MATRIX_HEIGHT);

            // cut smallest square around the letter
            Rectangle letterSquare = this.TrimLetter(new Bitmap(pic));

            // resize it
            Graphics graphics = Graphics.FromImage(bitmapPic);
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.DrawImage(pic,
                new Rectangle(0, 0, this.MATRIX_WIDTH, this.MATRIX_HEIGHT),
                letterSquare,
                GraphicsUnit.Pixel);

            // convert data to int[][]
            int[][] resultMatrix = this.DataToString(ref bitmapPic);

            graphics.Dispose();
            bitmapPic.Dispose();
            pic.Dispose();

            return resultMatrix;
        }
Beispiel #6
0
        private void UploadImage()
        {
            System.Drawing.Image image  = null;
            System.Drawing.Image image2 = null;
            Bitmap       bitmap         = null;
            Graphics     graphics       = null;
            MemoryStream memoryStream   = null;

            try
            {
                HttpPostedFile httpPostedFile = base.Request.Files["Filedata"];
                string         str            = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                string         str2           = HiContext.Current.GetPCHomePageSkinPath() + "/UploadImage/" + this.slsbannerposition.Value + "/";
                string         text           = str + Path.GetExtension(httpPostedFile.FileName);
                httpPostedFile.SaveAs(Globals.MapPath(str2 + text));
                base.Response.StatusCode = 200;
                base.Response.Write(HiContext.Current.GetPCHomePageSkinPath() + "/UploadImage/" + this.slsbannerposition.Value + "/" + text);
            }
            catch (Exception)
            {
                base.Response.StatusCode = 500;
                base.Response.Write("服务器错误");
                base.Response.End();
            }
            finally
            {
                bitmap?.Dispose();
                graphics?.Dispose();
                image2?.Dispose();
                image?.Dispose();
                memoryStream?.Close();
                base.Response.End();
            }
        }
        public static Image<Gray, byte> DetectAndTrimFace(int[] pixels, Size initialSize, Size outputSize, String haarcascadePath)
        {
            var inBitmap = ConvertToBitmap(pixels, initialSize.Width, initialSize.Width);

            //for testing purposes I can the picture to a folder
            //inBitmap.Save(@"E:\data\phototest\received.bmp");

            var grayframe = new Image<Gray, byte>(inBitmap);

            var haar = new HaarCascade(haarcascadePath);
            var faces = haar.Detect(grayframe,
                1.2,
                3,
                HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                new Size(30, 30));

            if (faces.Count() != 1)
            {
                return null;
            }
            var face = faces[0];

            var returnImage = grayframe.Copy(face.rect).Resize(outputSize.Width, outputSize.Height, INTER.CV_INTER_CUBIC);

            //cleanup managed resources
            haar.Dispose();
            grayframe.Dispose();

            return returnImage;
        }
Beispiel #8
0
        public void Add(Image img)
        {
            _list.Add(GetBytes(img));

            // stored image data, now dispose of original
            img.Dispose();
        }
    protected void LoadImage()
    {
        DBconnection obj = new DBconnection();

        obj.SetCommandQry = "select top 2 * from tblImgData order by id desc";
        DataTable dt = new DataTable();

        dt = obj.ExecuteTable();
        if (dt.Rows.Count > 0)
        {
            byte[] barrImg = (byte[])dt.Rows[0]["Picture"];
            Session["Image"] = barrImg;
            System.IO.MemoryStream mstream = new System.IO.MemoryStream(barrImg, 0, barrImg.Length);
            System.Drawing.Image   img     = System.Drawing.Image.FromStream(mstream);

            img.Save(Server.MapPath("~/MyImage/test2.jpg"));
            Image1.ImageUrl = "~/MyImage/test2.jpg"; //Server.MapPath("../Image/test3.jpg");
            Image1.Height   = 100;
            Image1.Width    = 150;
            mstream.Close();
            img.Dispose();

            // Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(barrImg);
        }
    }
Beispiel #10
0
        /// <summary>
        /// resmi yeniden boyutlandır.
        /// </summary>
        /// <param name="imgToResize">boyutlandırılacak resim</param>
        /// <param name="size">boyutlar</param>
        /// <returns>Image titipnde bir resim</returns>
        public static Image ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

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

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

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

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

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            imgToResize.Dispose();

            return (Image)b;
        }
Beispiel #11
0
        public static Image ResizeImage(double scaleFactor, Image image)
        {
            MemoryStream stream = new MemoryStream();

            var newWidth = (int)(image.Width * scaleFactor);
            var newHeight = (int)(image.Height * scaleFactor);
            var thumbnailBitmap = new Bitmap(newWidth, newHeight);

            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbnailGraph.DrawImage(image, imageRectangle);

            thumbnailBitmap.Save(stream, image.RawFormat);

            Image returnImage = Image.FromStream(stream);

            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
            image.Dispose();

            return returnImage;
        }
Beispiel #12
0
        /// <summary>
        /// Most of the time it just returns a black screen, this is because the game is rendering straight to the 
        /// graphics card using directx and bypassing whatever windows usually uses for PrintWindow 
        /// AFAIK directx screenshots only work if the window is currently visible (not overlaid by the bot itself)
        /// </summary>
        /// <returns></returns>
        public Image<Bgr, byte> TakeScreenshot()
        {
            Bitmap frame = new Bitmap(1024, 768);
            using (Graphics g = Graphics.FromImage(frame))
            {
                IntPtr deviceContextHandle = g.GetHdc();
                PrintWindow(GetGameWindowHandle(), deviceContextHandle, 1);
                g.ReleaseHdc();
            }
            //we have the bitmap now
            //turn it into an Image for emgu
            BitmapData bmpData = frame.LockBits(new Rectangle(0, 0, frame.Width, frame.Height), ImageLockMode.ReadWrite,
                                                PixelFormat.Format24bppRgb);

            Image<Bgr, byte> tempImage = new Image<Bgr, byte>(frame.Width, frame.Height, bmpData.Stride, bmpData.Scan0);
            //to prevent any corrupted memory errors that crop up for some reason
            Image<Bgr, byte> image = tempImage.Clone();
            frame.UnlockBits(bmpData);
            //dispose all unused image data to prevent memory leaks
            frame.Dispose();
            tempImage.Dispose();
            image.Save("screenshot.png");

            return image;
        }
        public static Image Crop(Image Image, int newWidth, int newHeight, int startX = 0, int startY = 0)
        {
            if (Image.Height < newHeight)
                newHeight = Image.Height;

            if (Image.Width < newWidth)
                newWidth = Image.Width;

            using (var bmp = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb))
            {
                bmp.SetResolution(72, 72);
                using (var g = Graphics.FromImage(bmp))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    g.DrawImage(Image, new Rectangle(0, 0, newWidth, newHeight), startX, startY, newWidth, newHeight, GraphicsUnit.Pixel);

                    var ms = new MemoryStream();
                    bmp.Save(ms, ImageFormat.Png);
                    Image.Dispose();
                    var outimage = Image.FromStream(ms);
                    return outimage;
                }
            }
        }
Beispiel #14
0
 public Image Process(Image inputImage, out bool isProcessed)
 {
     if (this.TargetSize.Height > inputImage.Height && this.TargetSize.Width > inputImage.Width)
     {
         isProcessed = false;
         return inputImage;
     }
     Size arg_39_0 = inputImage.Size;
     Rectangle cropArea = this.CropArea;
     int num = cropArea.X + cropArea.Width;
     if (num > inputImage.Width)
     {
         cropArea.Width -= num - inputImage.Width;
     }
     int num2 = cropArea.Y + cropArea.Height;
     if (num2 > inputImage.Height)
     {
         cropArea.Height -= num2 - inputImage.Height;
     }
     Bitmap bitmap = new Bitmap(this.TargetSize.Width, this.TargetSize.Height);
     using (Graphics graphics = Graphics.FromImage(bitmap))
     {
         graphics.InterpolationMode = this.InterpoliationMode;
         graphics.SmoothingMode = this.SmoothingMode;
         Rectangle destRect = new Rectangle(0, 0, this.TargetSize.Width, this.TargetSize.Height);
         graphics.DrawImage(inputImage, destRect, cropArea, GraphicsUnit.Pixel);
     }
     inputImage.Dispose();
     isProcessed = true;
     return bitmap;
 }
 public PagingImage(string filename)
 {
     _filename = filename;
     img = Bitmap.FromFile(filename);
     _pages = img.GetFrameCount(FrameDimension.Page);
     img.Dispose();
 }
Beispiel #16
0
    public bool ThumbImage(string originalFile, string newFile, int width, int height)
    {
        try
        {
            // Create an Image object from a file.

            // PhotoTextBox.Text is the full path of your image

            using (System.Drawing.Image photoImg = System.Drawing.Image.FromFile(originalFile))
            {
                // Create a Thumbnail from image with size 50x40.

                // Change 50 and 40 with whatever size you want

                using (System.Drawing.Image thumbPhoto = photoImg.GetThumbnailImage(width, height, null, new System.IntPtr()))
                {
                    // The below code converts an Image object to a byte array

                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] imgBytes = ms.ToArray();
                        thumbPhoto.Dispose();
                        photoImg.Dispose();
                        return(ByteArrayToFile(newFile, imgBytes));
                    }
                }
            }
        }
        catch (Exception exp)
        {
            return(false);
        }
    }
Beispiel #17
0
        private void DrawImage(string filePath, string xueHao, string name, float xPosition, float yPosition)
        {
            System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(filePath);
            sourceImage.RotateFlip(RotateFlipType.Rotate90FlipXY);
            Bitmap newImage = new Bitmap(sourceImage, sourceImage.Width, sourceImage.Height);

            //newImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
            newImage.SetResolution(100, 100);            //设置分辨率的大小
            Graphics gh = Graphics.FromImage(newImage);

            gh.SmoothingMode = SmoothingMode.HighQuality;
            gh.DrawImage(newImage, new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel);
            Font  newFont  = null;
            SizeF fontSize = new SizeF();

            newFont  = new Font("黑体", 22, FontStyle.Bold);
            fontSize = gh.MeasureString(xueHao, newFont);
            StringFormat format = new StringFormat();

            format.Alignment = StringAlignment.Center;
            SolidBrush brush = new SolidBrush(Color.White);

            gh.DrawString(xueHao, newFont, brush, new PointF(xPosition, yPosition), format);
            newImage.RotateFlip(RotateFlipType.Rotate270FlipXY);
            gh.DrawString(AddSplit(name), newFont, brush, new PointF(sourceImage.Height - yPosition - 13, xPosition + 109), format);
            newImage.Save(filePath, ImageFormat.Jpeg);
            gh.Dispose();
            sourceImage.Dispose();
        }
Beispiel #18
0
 static void Main(string[] args)
 {
     var img = new Image<Bgr, byte>(@"src.jpg");
     var w = img.Width;
     var h = img.Height;
     var r0 = 512;   // half of the image size
     var p = 0.5;    // control the "height"
     var phi0 = -Math.PI / 2 + 0.12;    // initial phase
     var newImg = new Image<Bgr, byte>(r0 * 2, r0 * 2, new Bgr(Color.White));
     for (int row = 0; row < r0 * 2; row++)
     {
         for (int col = 0; col < r0 * 2; col++)
         {
             var phi = (Math.Atan2(row - r0, col - r0) + phi0);
             if (phi > Math.PI) phi -= 2 * Math.PI;
             if (phi < -Math.PI) phi += 2 * Math.PI;
             var r = Math.Sqrt((row - r0) * (row - r0) + (col - r0) * (col - r0));
             r = Math.Pow(r0, 1 - p) * Math.Pow(r, p);
             var y = (int)(h - r / r0 * h);
             var x = (int)((phi + Math.PI) / Math.PI / 2 * w);
             if (y >= 0 && y < h && x >= 0 && x < w)
                 newImg[row, col] = img[y, x];
         }
     }
     newImg.Save("result.jpg");
     newImg.Dispose();
     img.Dispose();
 }
Beispiel #19
0
		public static Image ResizeImage (Image img, string path, Size maxSize) {
			// Mono for mac uses a better system.drawing implementation; fall back to graphicsmagick on linux
			if (Extensions.IsRunningOnMac) {
				var maxAspect = (float)maxSize.Width / (float)maxSize.Height;
				var imgAspect = (float)img.Width / (float)img.Height;

				if (imgAspect > maxAspect)
					return new Bitmap(img, new Size(maxSize.Width, (int)Math.Round(maxSize.Width / imgAspect)));
				else
					return new Bitmap(img, new Size((int)Math.Round(maxSize.Height * imgAspect), maxSize.Height));
			} else {
				img.Dispose();
				var wand = GraphicsMagick.NewWand();
				GraphicsMagick.ReadImageBlob(wand, File.OpenRead(path));

				var maxAspect = (float)maxSize.Width / (float)maxSize.Height;
				var imgAspect = (float)GraphicsMagick.GetWidth(wand) / (float)GraphicsMagick.GetHeight(wand);

				if (imgAspect > maxAspect)
					GraphicsMagick.ResizeImage(wand, (IntPtr)maxSize.Width, (IntPtr)Math.Round(maxSize.Width / imgAspect), GraphicsMagick.Filter.Box, 1);
				else
					GraphicsMagick.ResizeImage(wand, (IntPtr)Math.Round(maxSize.Height * imgAspect), (IntPtr)maxSize.Height, GraphicsMagick.Filter.Box, 1);
				var newImgBlob = GraphicsMagick.WriteImageBlob(wand);

				using (var ms = new MemoryStream(newImgBlob)) {
					return Image.FromStream(ms);
				}
			}
		}
    private byte[] BmpToBytes(System.Drawing.Image bmp)
    {
        MemoryStream ms = null;

        byte[] bmpBytes = null;
        try
        {
            ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            // read to end
            bmpBytes = ms.GetBuffer();
        }
        catch (Exception ex)
        {
            return(null);
        }
        finally
        {
            bmp.Dispose();
            if (ms != null)
            {
                ms.Close();
            }
        }
        return(bmpBytes);
    }
Beispiel #21
0
        protected async Task UpdateSource()
        {
            var element = Element;

            if (element != null)
            {
                element.SetIsLoading(true);
                try
                {
                    _source?.Dispose();
                    _source = null;

                    var source = Element.Source;
                    IImageSourceHandler handler;
                    if (source != null && (handler = Registrar.Registered.GetHandler <IImageSourceHandler>(source.GetType())) != null)
                    {
                        try
                        {
                            _source = await handler.LoadImageAsync(source);
                        }
                        catch (OperationCanceledException)
                        {
                        }

                        RefreshImage();
                    }
                }
                finally
                {
                    element.SetIsLoading(false);
                }

                Control?.Invalidate();
            }
        }
Beispiel #22
0
    /// <summary>
    /// 生成二维码图片
    /// </summary>
    /// <param name="URL"></param>
    /// <param name="WebPath"></param>
    /// <returns></returns>
    public static string CreateQRCodeImg(string URL, string WebPath)
    {
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

        qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;   //编码方式(注意:BYTE能支持中文,ALPHA_NUMERIC扫描出来的都是数字)
        qrCodeEncoder.QRCodeScale        = 40;                               //大小(值越大生成的二维码图片像素越高)
        qrCodeEncoder.QRCodeVersion      = 0;                                //版本(注意:设置为0主要是防止编码的字符串太长时发生错误)
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; //错误效验、错误更正(有4个等级)

        //System.Drawing.Image image = qrCodeEncoder.Encode("4408810820 深圳-广州 小江");
        System.Drawing.Image image = qrCodeEncoder.Encode(URL);
        string filename            = Guid.NewGuid().ToString() + ".png";

        //物理路径
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(WebPath)))//判断文件夹路径是否存在
        {
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(WebPath));
        }
        string filepath = HttpContext.Current.Server.MapPath(WebPath + "\\" + filename);

        System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
        image.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
        fs.Close();
        image.Dispose();

        return(WebPath + "/" + filename);
    }
Beispiel #23
0
        public static void MakeSquareImage(Image image, string newFileName, int newSize)
        {
            int width = image.Width;
            int height = image.Height;

            var b = new Bitmap(newSize, newSize);

            try
            {
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;

                g.Clear(Color.Transparent);
                g.DrawImage(image, new Rectangle(0, 0, newSize, newSize),
                            width < height
                                ? new Rectangle(0, (height - width)/2, width, width)
                                : new Rectangle((width - height)/2, 0, height, height), GraphicsUnit.Pixel);

                SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
            }
            finally
            {
                image.Dispose();
                b.Dispose();
            }
        }
Beispiel #24
0
 public Image CheckValidImage(Image img, int width, int height)
 {
     if (img == null) return null;
     Bitmap bmp = new Bitmap(width, height);
     try
     {
         using (Graphics g = Graphics.FromImage(bmp))
         {
             g.InterpolationMode = InterpolationMode.HighQualityBicubic;
             g.PixelOffsetMode = PixelOffsetMode.HighQuality;
             g.DrawImage(img, 0, 0, width, height);
         }
         bmp.Tag = img.Tag;
         return bmp;
     }
     catch (Exception)
     {
         bmp.Dispose();
         bmp = new Bitmap(width, height);
         bmp.Tag = img.Tag;
         return bmp;
     }
     finally
     {
         img.Dispose();
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = DA.GETART(Request.QueryString["Id"].ToString());

        if (dt.Rows.Count > 0)
        {
            if (!(dt.Rows[0]["art_img"] is DBNull))
            {
                byte[] imageByte = (byte[])dt.Rows[0]["art_img"];

                System.IO.MemoryStream MS  = new System.IO.MemoryStream(imageByte);
                System.Drawing.Image   img = System.Drawing.Image.FromStream(MS);

                int width = 100;
                if (Request.QueryString["w"] != null)
                {
                    width = int.Parse(Request.QueryString["w"]);
                }

                int heigh = width * img.Height / img.Width;

                System.Drawing.Image thump = img.GetThumbnailImage(width, heigh, null, IntPtr.Zero);
                thump.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                img.Dispose();
                thump.Dispose();
            }
        }
    }
Beispiel #26
0
 public void Dispose()
 {
     _sdimage?.Dispose();
     _bitmap?.Dispose();
     _sdimage = null;
     _bitmap  = null;
 }
Beispiel #27
0
            /// <summary>
            /// Convert Tiff image to another mime-type bitmap
            /// </summary>
            /// <param name="tiffImage">Source TIFF file</param>
            /// <param name="mimeType">Desired result mime-type</param>
            /// <returns>Converted image</returns>
            public Bitmap ConvertTiffToBitmap(Image tiffImage, string mimeType)
            {
                var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == "image/tiff");

                if (imageCodecInfo == null)
                {
                    return null;
                }
                Bitmap sourceImg;

                using (var memoryStream = new MemoryStream())
                {
                    // Setting encode params
                    var imageEncoderParams = new EncoderParameters(1);
                    imageEncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    tiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);
                    tiffImage.Dispose();

                    var ic = new ImageConverter();

                    // Reading stream data to new image
                    var tempTiffImage = (Image)ic.ConvertFrom(memoryStream.GetBuffer());

                    // Setting new result mime-type
                    imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == mimeType);
                    if (tempTiffImage != null) tempTiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);

                    sourceImg = new Bitmap(Image.FromStream(memoryStream, true));

                }

                return sourceImg;
            }
Beispiel #28
0
    private void MakeThumbImage(string sPath, string stPath, int nWidth, int nHeight)
    {
        System.Drawing.Image sImage = System.Drawing.Image.FromFile(sPath);
        int tw = nWidth;
        int th = nHeight;
        ///原始图片的宽度和高度
        int sw = sImage.Width;
        int sh = sImage.Height;

        if (sw > tw)
        {
            sw = tw;
        }
        if (sh > th)
        {
            sh = th;
        }
        System.Drawing.Bitmap objPic, objNewPic;
        objPic    = new System.Drawing.Bitmap(sPath);
        objNewPic = new System.Drawing.Bitmap(objPic, sw, sh);
        objNewPic.Save(stPath);
        sImage.Dispose();
        objPic.Dispose();
        objNewPic.Dispose();
    }
Beispiel #29
0
    public static void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int NewHeight)
    {
        try
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            //The user only set the width, calculate the new height
            if (NewWidth > 0 && NewHeight == 0)
            {
                NewHeight = (int)Math.Floor((double)FullsizeImage.Height / ((double)FullsizeImage.Width / (double)NewWidth));
            }

            //The user only set the height, calculate the width
            if (NewHeight > 0 && NewWidth == 0)
            {
                NewWidth = (int)Math.Floor((double)FullsizeImage.Width / ((double)FullsizeImage.Height / (double)NewHeight));
            }

            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);
        }
        catch (Exception)
        { }
    }
Beispiel #30
0
 //生成缩略图并保存
 public void SaveImgs(string oPath)
 {
     Chc.Request.Files[0].SaveAs(oPath);
     System.Drawing.Image Img = System.Drawing.Image.FromFile(oPath);
     System.Drawing.Image TI  = Img.GetThumbnailImage(96, 64, Tc, System.IntPtr.Zero);
     TI.Save(oPath.Insert(oPath.LastIndexOf("\\") + 1, "Thumbnail\\"), ICI(), Eps(90));
     Img.Dispose();
 }
Beispiel #31
0
 private static void saveFile(string filenamepart1, ImageSizeType ist, Image imsmall)
 {
     MemoryStream imagestream = new MemoryStream();
     imsmall.Save(imagestream, System.Drawing.Imaging.ImageFormat.Jpeg);
     CBB.MongoDB.GridFSHelper.UploadFile(imagestream, filenamepart1 + ist.extname + ".jpg");
     imsmall.Dispose();
     imagestream.Dispose();
 }
Beispiel #32
0
        public static void FreeImageFile(Image image)
        {
            var path = imageDict.KeyByValue(image);
            if (path == null) return;

            image.Dispose();
            imageDict.Remove(path);
        }
Beispiel #33
0
 public static byte[] BitmapToBytes(Image image)
 {
     MemoryStream stream = new MemoryStream();
     image.Save(stream, ImageFormat.Jpeg);
     byte[] Bytes = stream.GetBuffer();
     image.Dispose();
     stream.Close();
     return Bytes;
 }
 public Image GetPage(int page)
 {
     if (page < 1 || page > _pages) return null;
     img = Bitmap.FromFile(_filename);
     img.SelectActiveFrame(FrameDimension.Page, page - 1);
     Image ret = new Bitmap(img);
     img.Dispose();
     return ret;
 }
 /// <summary>
 /// New WeakImage
 /// </summary>
 /// <param name="image">The image to cache.</param>
 /// <param name="forceImageDispose">Set to true to dispose the image immediatelly.</param>
 public WeakImage(Image image, bool forceImageDispose)
     : this()
 {
     Image = image;
     if (forceImageDispose)
     {
         image.Dispose(); image = null;
     }
 }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            int ID = Convert.ToInt32(Request.QueryString["ID"]);
            var kategoriGuncelle = db.ETICARET_Kategoris.Where(m => m.ID == ID).FirstOrDefault();

            int resimvitrin, altmenu, durum;
            resimvitrin = (chkResimVitrin.Checked) ? 1 : 0;
            altmenu     = (chkAltmenu.Checked) ? 1 : 0;
            durum       = (chkDurum.Checked) ? 1 : 0;

            string dosyaAdi;
            if (fuKategori.HasFile)
            {
                string filenameadd = DateTime.Now.ToString().Replace(" ", "_").Replace(":", "_").Replace(".", "_").Replace("/", "_");
                string uzanti      = Path.GetExtension(fuKategori.FileName);
                dosyaAdi = filenameadd + uzanti;
                fuKategori.PostedFile.SaveAs(Server.MapPath("~/Dosyalar/Kategori/") + dosyaAdi);

                System.Drawing.Image imgResim         = null;
                System.Drawing.Image imgOrijinalResim = System.Drawing.Image.FromFile(Server.MapPath("~/Dosyalar/Kategori/" + dosyaAdi));
                imgResim = resimboyutlandir.FixedSize(imgOrijinalResim, 290, 290);
                imgResim.Save(Server.MapPath("~/Dosyalar/Kategori/Mini/" + dosyaAdi));
                imgResim.Dispose();
            }
            else
            {
                dosyaAdi = kategoriGuncelle.Resim;
            }

            kategoriGuncelle.KategoriAdi = txtKategoriAdi.Text;
            kategoriGuncelle.Detay       = txtDetay.Text;
            kategoriGuncelle.Title       = txtTitle.Text;
            kategoriGuncelle.Description = txtDescription.Text;
            kategoriGuncelle.Keywords    = txtKeywords.Text;
            kategoriGuncelle.Resim       = dosyaAdi;
            kategoriGuncelle.Durum       = durum;
            kategoriGuncelle.ResimVitrin = resimvitrin;
            kategoriGuncelle.Alt         = altmenu;
            kategoriGuncelle.AltID       = Convert.ToInt32(drpKategoriler.SelectedValue);
            kategoriGuncelle.Sira        = txtSira.Text;

            db.SubmitChanges();



            pnlHata.Visible     = false;
            pnlBasarili.Visible = true;
            Page.Header.Controls.Add(new LiteralControl("<meta http-equiv='refresh' content='2; url=kategoriler.aspx'/>"));
        }
        catch (Exception)
        {
            pnlHata.Visible     = true;
            pnlBasarili.Visible = false;
        }
    }
    protected override void OnLoad(EventArgs e)
    {
      _image = new Bitmap(100, 100);
      _image.Dispose();

      imageBox.Image = _image;

      base.OnLoad(e);
    }
Beispiel #38
0
        public void ApplyWatermark(string imageId, string watermarkImageId)
        {
            var imagePath       = GetImagePath(imageId, null);
            var backupImagePath = GetOriginalImagePath(imageId);
            var watermarkPath   = GetImagePath(watermarkImageId, null);

            try
            {
                Image img = null;
                // не пихаем всё сразу в кучу юзингов, потому что потом картинку по тому же урлу нельзя будет сохранить
                try
                {
                    using (FileStream source = new FileStream(imagePath, FileMode.Open))
                    {
                        img = Image.FromStream(source);
                        using (FileStream watermarkSource = new FileStream(watermarkPath, FileMode.Open))
                            using (Image watermarkImg = Image.FromStream(watermarkSource))
                            {
                                if (img.Width < watermarkImg.Width || img.Height < watermarkImg.Height)
                                {
                                    return;
                                }

                                if (!File.Exists(backupImagePath))
                                {
                                    CreateDirectoryForPath(backupImagePath);
                                    File.Copy(imagePath, backupImagePath);
                                }

                                using (Graphics imageGraphics = Graphics.FromImage(img))
                                    using (TextureBrush watermarkBrush = new TextureBrush(watermarkImg))
                                    {
                                        int x = img.Width / 2 - watermarkImg.Width / 2;
                                        int y = img.Height / 2 - watermarkImg.Height / 2;
                                        watermarkBrush.TranslateTransform(x, y);
                                        imageGraphics.FillRectangle(watermarkBrush,
                                                                    new Rectangle(new Point(x, y),
                                                                                  new Size(watermarkImg.Width + 1, watermarkImg.Height)));
                                    }
                            }
                    }
                    ImageFormat format = FilenameToImageFormat(imageId);
                    img.Save(imagePath, format);
                    DeleteThumbnails(imageId);
                }
                finally
                {
                    // using не подойдёт, ибо в начале объект - null
                    img?.Dispose();
                }
            }
            catch (Exception e)
            {
                _logService.LogError(e);
            }
        }
Beispiel #39
0
 public static void SaveToJpgFile(System.Drawing.Image img, string fileName)
 {
     if (!File.Exists(fileName))
     {
         System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img, img.Width, img.Height);
         bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
         bmp.Dispose();
         img.Dispose();
     }
 }
Beispiel #40
0
        /// <summary>
        /// Create screen shot of image for training purposes
        /// </summary>
        /// <param name="inImg">image to capture from</param>
        /// <param name="count">sequence number to use</param>
        /// <param name="type">positive or negative</param>
        public static void saveBitMapToDisk(Image toSave, int count, string type, int subCount)
        {
            string posPath = Path.Combine("../../Images/", type, "hand_" + count + "_"+subCount+".png");

            Console.WriteLine("saving image:" + posPath);

            toSave.Save(posPath, ImageFormat.Png);

            toSave.Dispose();
        }
Beispiel #41
0
 /// <summary>
 /// 在图片上生成图片水印
 /// </summary>
 /// <param name="Path">原服务器图片路径</param>
 /// <param name="Path_syp">生成的带图片水印的图片路径</param>
 /// <param name="Path_sypf">水印图片路径</param>
 public static void AddWaterPic(string Path, string Path_syp, string Path_sypf)
 {
     System.Drawing.Image    image     = System.Drawing.Image.FromFile(Path);
     System.Drawing.Image    copyImage = System.Drawing.Image.FromFile(Path_sypf);
     System.Drawing.Graphics g         = System.Drawing.Graphics.FromImage(image);
     g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
     g.Dispose();
     image.Save(Path_syp);
     image.Dispose();
 }
        public static void MergeImages(Image background, Image foreground, HttpContext context)
        {
            if (background == null)
                throw new ArgumentNullException("background");

            if (foreground == null)
                throw new ArgumentNullException("foreground");

            // if ratio is > 120/90
            //  define by width
            // else
            // define by height
            double ratioForeGround = foreground.Width/(float)foreground.Height;

            int foreGroundWidth = background.Width;
            int foreGroundHeight = background.Height;
            if (ratioForeGround > 1)
            {
                foreGroundHeight = (int)(background.Height * (background.Height/foreground.Height));
            }
            else
            {
                foreGroundWidth = (int)(background.Height * (foreground.Width / (float)foreground.Height));
            }

            using (background)
            {
                using (var bitmap = new Bitmap(background.Width, background.Height))
                {
                    using (var canvas = Graphics.FromImage(bitmap))
                    {
                        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        canvas.DrawImage(background, new Rectangle(0, 0, background.Width, background.Height), new Rectangle(0, 0, background.Width, background.Height), GraphicsUnit.Pixel);
                        // canvas.DrawImage(foreground, (bitmap.Width / 2) - (foreGroundWidth / 2 + 5), (bitmap.Height / 2) - (foreGroundWidth / 2 + 5));
                        canvas.DrawImage(foreground, (bitmap.Width / 2) - (foreGroundWidth / 2 + 5), (bitmap.Height / 2) - (foreGroundHeight / 2 + 5), foreGroundWidth, foreGroundHeight);
                        canvas.Save();
                    }
                    try
                    {
                        context.Response.ContentType = "image/png";
                        bitmap.Save(context.Response.OutputStream, ImageFormat.Png);
                    }
                    catch (Exception)
                    {
                        // no action
                    }
                    finally
                    {
                        background.Dispose();
                        foreground.Dispose();

                    }
                }
            }
        }
Beispiel #43
0
    protected void Button2_Click(object sender, ImageClickEventArgs e)
    {
        string path = Server.MapPath(imgPhoto.ImageUrl);

        System.Drawing.Image img = System.Drawing.Image.FromFile(path);
        img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipXY);

        img.Save(path);
        img.Dispose();
        imgPhoto.Attributes.Add("ImageUrl", path);
    }
Beispiel #44
0
    /// <summary>
    /// 在图片上添加图片水印
    /// </summary>
    /// <param name="path">原服务器上的图片路径</param>
    /// <param name="syPicPath">水印图片的路径</param>
    /// <param name="waterPicPath">生成的水印图片存放路径</param>
    public static void AddWaterPic(Stream path, Stream syPicPath, string waterPicPath,int x,int y,int width,int height)
    {
        System.Drawing.Image image = System.Drawing.Image.FromStream(path);
        System.Drawing.Image waterImage = System.Drawing.Image.FromStream(syPicPath);
        System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(image);
        graphic.DrawImage(waterImage, new System.Drawing.Rectangle(x, y, width, height), 0, 0, waterImage.Width, waterImage.Height, System.Drawing.GraphicsUnit.Pixel);
        graphic.Dispose();

        image.Save(waterPicPath);
        image.Dispose();
    }
    private void DisplayError()
    {
        System.Drawing.Image ImgError       = System.Drawing.Image.FromFile(Server.MapPath("../Resources/nophoto.gif"));
        MemoryStream         NewImageStream = new MemoryStream();

        ImgError.Save(NewImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        ImgError.Dispose();

        //returning the Croped image as byte stream
        Response.BinaryWrite(NewImageStream.GetBuffer());
    }
        public static void ConverToGifImageWithNewColor(ref Image refImage, ColorPalette refPalette, Color victimColor, Color newColor)
        {
            ReplaceColorInPalette(ref refImage, refPalette, victimColor, newColor);

            // Rewrite the bitmap data in a new image
            Image gifImage = Core.GifImage.CreateGifImage(ref refImage);

            refImage.Dispose();

            refImage = gifImage;
        }
Beispiel #47
0
 /// <summary>
 /// Inserts an image into the HttpCache and returns the cache identifier.
 /// </summary>
 /// <remarks>
 /// Image can after insertion into the cache be requested by calling getmap.aspx?ID=[identifier]<br/>
 /// This requires you to add the following to web.config:
 /// <code escaped="true">
 /// <httpHandlers>
 ///	   <add verb="*" path="GetMap.aspx" type="SharpMap.Web.HttpHandler,SharpMap"/>
 /// </httpHandlers>
 /// </code>
 /// <example>
 /// Inserting the map into the cache and setting the ImageUrl:
 /// <code>
 /// string imgID = SharpMap.Web.Caching.CacheMap(5, myMap.GetMap(), Session.SessionID, Context);
 /// imgMap.ImageUrl = "getmap.aspx?ID=" + HttpUtility.UrlEncode(imgID);
 /// </code>
 /// </example>
 /// </remarks>
 /// <param name="minutes">Number of minutes to cache the map</param>
 /// <param name="map">Map reference</param>
 /// <returns>Image identifier</returns>
 public static string InsertIntoCache(int minutes, Image map)
 {
     string guid = Guid.NewGuid().ToString().Replace("-", "");
     MemoryStream MS = new MemoryStream();
     map.Save(MS, ImageFormat.Png);
     byte[] buffer = MS.ToArray();
     HttpContext.Current.Cache.Insert(guid, buffer, null, Cache.NoAbsoluteExpiration,
                                      TimeSpan.FromMinutes(minutes));
     map.Dispose();
     return guid;
 }
Beispiel #48
0
    /// <summary>
    /// 文件保存
    /// </summary>
    /// <param name="fileNameDesc"></param>
    /// <param name="File1"></param>
    /// <returns></returns>
    private SysFileManager FileSave(string fileNameDesc, HtmlInputFile File1, Entity myen)
    {
        SysFileManager en = new SysFileManager();

        en.EnName = myen.ToString();
        // en.FileID = this.RefPK + "_" + count.ToString();
        EnCfg cfg = new EnCfg(en.EnName);

        string filePath = cfg.FJSavePath; // BP.SystemConfig.PathOfFDB + "\\" + this.EnName + "\\";

        if (System.IO.Directory.Exists(filePath) == false)
        {
            System.IO.Directory.CreateDirectory(filePath);
        }

        string ext = System.IO.Path.GetExtension(File1.PostedFile.FileName);

        ext          = ext.Replace(".", "");
        en.MyFileExt = ext;
        if (fileNameDesc == "" || fileNameDesc == null)
        {
            en.MyFileName = System.IO.Path.GetFileNameWithoutExtension(File1.PostedFile.FileName);
        }
        else
        {
            en.MyFileName = fileNameDesc;
        }
        en.RDT        = DataType.CurrentData;
        en.RefVal     = myen.PKVal.ToString();
        en.MyFilePath = filePath;
        en.Insert();

        string fileName = filePath + en.OID + "." + en.MyFileExt;

        File1.PostedFile.SaveAs(fileName);

        File1.PostedFile.InputStream.Close();
        File1.PostedFile.InputStream.Dispose();
        File1.Dispose();

        System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
        en.MyFileSize = DataType.PraseToMB(fi.Length);

        if (DataType.IsImgExt(en.MyFileExt))
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(fileName);
            en.MyFileH = img.Height;
            en.MyFileW = img.Width;
            img.Dispose();
        }
        en.WebPath = cfg.FJWebPath + en.OID + "." + en.MyFileExt;
        en.Update();
        return(en);
    }
 public static string ApplyBradleyLocalThresholding(string inputPath, string outputPath)
 {
     AForge.Imaging.Filters.BradleyLocalThresholding bradley = new AForge.Imaging.Filters.BradleyLocalThresholding();
     Image<Gray, Byte> img = new Image<Gray, Byte>(inputPath);
     Bitmap dstimg = bradley.Apply(img.Bitmap);
     dstimg.Save(outputPath);
     dstimg.Dispose();
     dstimg = null;
     img.Dispose();
     img = null;
     return outputPath;
 }
Beispiel #50
0
 public void SendMessage(Image image)
 {
     // 显示保存对话框
     var dialog = new SaveFileDialog();
     dialog.FileName = DateTime.Now.ToString("yyyyMMdd-HHmmssffff") + ".PNG";
     dialog.Filter = "PNG图像 | *.PNG";
     if (DialogResult.OK == dialog.ShowDialog())
     {
         image.Save(dialog.FileName, ImageFormat.Png);
     }
     image.Dispose();
 }
Beispiel #51
0
 public void HideBytesInPng(Image innocuousBmp, string outputImageFileName, byte[] hiddenBytes)
 {
     hiddenBytes = ByteEncryptionUtil.EncryptSalsa20(hiddenBytes, _key);
     byte[] hiddenLengthBytes = BitConverter.GetBytes(hiddenBytes.Length);
     byte[] hiddenCombinedBytes = PngUtils.Combine(hiddenLengthBytes, hiddenBytes);
     byte[] rgbComponents = PngUtils.RgbComponentsToBytes(innocuousBmp);
     byte[] encodedRgbComponents = EncodeBytes(hiddenCombinedBytes, rgbComponents);
     Bitmap encodedBmp = PngUtils.ByteArrayToBitmap(encodedRgbComponents, innocuousBmp.Width, innocuousBmp.Height);
     encodedBmp.Save(outputImageFileName, ImageFormat.Png);
     encodedBmp.Dispose();
     innocuousBmp.Dispose();
 }
Beispiel #52
0
    protected void lbvisualizar_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuimagen.HasFile)
            {
                string fileName  = Server.HtmlEncode(fuimagen.FileName);
                string extension = System.IO.Path.GetExtension(fileName);
                if ((extension == ".jpg") | (extension == ".bmp") | (extension == ".BMP") | (extension == ".JPG") | (extension == ".PNG") | (extension == ".png") | (extension == ".GIF") | (extension == ".gif"))
                {
                    classRandom sa = new classRandom();
                    savePath  = "";
                    savePath += sa.NextString(6, true, false, true, false);
                    savePath += extension;
                    fuimagen.PostedFile.SaveAs(Server.MapPath("..\\upload\\servicios\\") + savePath);
                    String ruta = Server.MapPath("..\\upload\\servicios\\" + savePath);
                    System.Drawing.Image objImage = System.Drawing.Image.FromFile(ruta);
                    //this.lbltamaño.Text = "Ancho de la imagen: " + objImage.Width.ToString() + "px, Alto de la imagen: " + objImage.Height.ToString() + "px";
                    int ancho = int.Parse(objImage.Width.ToString());
                    int alto  = int.Parse(objImage.Height.ToString());
                    objImage.Dispose();
                    objImage = null;

                    if ((ancho == 450) && (alto == 450))
                    {
                        img.ImageUrl = "~/upload/servicios/" + savePath;
                    }
                    else
                    {
                        // ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "click", "alert('Por favor seleccionar una imagen con el tamaño adecuado');", true);
                        pMensajesAlertas.Visible = true;
                        DMensaje.Attributes.Add("Class", "error");
                        DMensaje.InnerText = "Por favor seleccionar una imagen con el tamaño adecuado 450 x 450";
                    }
                }
                else
                {
                    pMensajesAlertas.Visible = true;
                    DMensaje.Attributes.Add("Class", "error");
                    DMensaje.InnerText = "Por favor seleccionar una imagen con el formato adecuado: jpg, bmp, gif, png";
                }
            }
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
            //ScriptManager.RegisterStartupScript(upMantenimiento, upMantenimiento.GetType(), "click", "alert('" + Ex.Message + "');", true);
            pMensajesAlertas.Visible = true;
            DMensaje.Attributes.Add("Class", "error");
            DMensaje.InnerText = Ex.Message;
        }
    }
Beispiel #53
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string link;
            if (txtLink.Text == "")
            {
                link = "#";
            }
            else
            {
                link = txtLink.Text;
            }

            string dosyaAdi;
            if (fuSlider.HasFile)
            {
                string filenameadd = DateTime.Now.ToString().Replace(" ", "_").Replace(":", "_").Replace(".", "_").Replace("/", "_");
                string uzanti      = Path.GetExtension(fuSlider.FileName);
                dosyaAdi = filenameadd + uzanti;
                fuSlider.PostedFile.SaveAs(Server.MapPath("~/Dosyalar/Slider/") + dosyaAdi);

                System.Drawing.Image imgResim         = null;
                System.Drawing.Image imgOrijinalResim = System.Drawing.Image.FromFile(Server.MapPath("~/Dosyalar/Slider/" + dosyaAdi));
                imgResim = resimboyutlandir.FixedSize(imgOrijinalResim, 1041, 492);
                imgResim.Save(Server.MapPath("~/Dosyalar/Slider/Mini/" + dosyaAdi));
                imgResim.Dispose();
            }
            else
            {
                dosyaAdi = "resimyok.jpg";
            }

            ETICARET_Banner ekle = new ETICARET_Banner()
            {
                Banner = dosyaAdi,
                Link   = link,
                Sira   = txtSira.Text,
            };

            db.ETICARET_Banners.InsertOnSubmit(ekle);
            db.SubmitChanges();
            pnlHata.Visible     = false;
            pnlBasarili.Visible = true;
            Page.Header.Controls.Add(new LiteralControl("<meta http-equiv='refresh' content='2; url=slider.aspx'/>"));
        }
        catch (Exception)
        {
            pnlHata.Visible     = true;
            pnlBasarili.Visible = false;
        }
    }
        /// <summary>
        /// Releases image from memory. Resolves memory leak.
        /// </summary>
        /// <remarks>
        /// http://stackoverflow.com/questions/871610/bitmap-save-huge-memory-leak
        /// </remarks>
        public static void ReleaseImage(Image image)
        {
            if (image == null)
                return;

            // Need to explictly call the garbage collecter after disposing.
            image.Dispose();
            image = null;

            //GC.Collect();
            //GC.WaitForPendingFinalizers();
            //GC.Collect();
        }
Beispiel #55
0
 public void Resize1(string DirectoryName, string FileName, bool DeleteAfterResize, string SavedFileName, int Width, int Hieght)
 {
     System.Drawing.Image NormalImg = System.Drawing.Image.FromFile(DirectoryName + "/" + FileName);
     System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
     System.Drawing.Image thumbNailImg = NormalImg.GetThumbnailImage(Width, Hieght, dummyCallBack, IntPtr.Zero);
     thumbNailImg.Save(DirectoryName + "/" + SavedFileName);
     NormalImg.Dispose();
     thumbNailImg.Dispose();
     if (DeleteAfterResize)
     {
         System.IO.File.Delete(DirectoryName + "/" + FileName);
     }
 }
    // get Thumbnail of uploaded image
    private byte[] getImage(Stream imageStream)
    {
        int maxWidth  = 100;
        int maxHeight = 100;

        byte[] buf = null;

        imageStream.Position = 0;
        System.Drawing.Image objImage = System.Drawing.Image.FromStream(imageStream);

        MemoryStream imageStreamN;

        System.Drawing.Image View;
        System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

        int mWidth  = objImage.Width;
        int mHeight = objImage.Height;

        if (mWidth > maxWidth)
        {
            mHeight = (int)((double)mHeight * ((double)maxWidth / (double)mWidth));
            mWidth  = maxWidth;
        }
        if (mHeight > maxHeight)
        {
            mWidth  = (int)((double)mWidth * ((double)maxHeight / (double)mHeight));
            mHeight = maxHeight;
        }

        if (mHeight == 0)
        {
            mHeight = 5;
        }
        if (mWidth == 0)
        {
            mWidth = 5;
        }

        View = objImage.GetThumbnailImage(mWidth, mHeight, myCallback, IntPtr.Zero);
        imageStream.Close();
        imageStreamN          = new MemoryStream();
        imageStreamN.Position = 0;
        View.Save(imageStreamN, objImage.RawFormat);
        View.Dispose();
        objImage.Dispose();
        imageStreamN.Position = 0;
        buf = new byte[(int)imageStreamN.Length];
        imageStreamN.Read(buf, 0, (int)imageStreamN.Length);
        imageStreamN.Close();
        return(buf);
    }
Beispiel #57
0
    protected void FormViewImageUpload_OnInserting(object sender, FormViewInsertEventArgs e)
    {
        //Primeira verificação: Verificar existência de ficheiro e fazer upload do thumbnail
        FileUpload fileUpload1 = (FileUpload)FormViewImageUpload.FindControl("FileUpload1");

        if (fileUpload1.HasFile)
        {
            if (fileUpload1.PostedFile.ContentType == "image/jpg" || fileUpload1.PostedFile.ContentType == "image/jpeg" || fileUpload1.PostedFile.ContentType == "image/pjpeg")
            {
                string path     = (Server.MapPath("~//files//content//images//" + fileUpload1.FileName));
                string ficheiro = fileUpload1.FileName;
                if (File.Exists(path))
                {
                    int contador = 0;
                    do
                    {
                        contador++;
                        ficheiro = Convert.ToString(contador) + ficheiro;
                        path     = (Server.MapPath("~//files//content//images//" + ficheiro));
                    } while (File.Exists(path) == true);
                }

                e.Values["filename"] = ficheiro;
                e.Values["type"]     = fileUpload1.PostedFile.ContentType;
                fileUpload1.SaveAs(Server.MapPath("~//files//content//images//" + ficheiro));
                //Get image data.
                System.Drawing.Image image = System.Drawing.Image.FromFile(path);
                string height = image.Height.ToString();
                string width  = image.Width.ToString();
                //string size = image.Size.ToString();
                image.Dispose();

                e.Values["width"]  = width;
                e.Values["height"] = height;
                e.Values["size"]   = fileUpload1.PostedFile.ContentLength.ToString();
            }
            else
            {
            }

            /*
             * Código para cancelar o insert no caso de falta de ficheiro :)
             * else
             * {
             *  e.Cancel = true;
             *
             * }
             */
        }
        //Fim de primeira verificação
    }
Beispiel #58
0
 public void makeThumbnail(string it, string Imageurl)
 {
     if (File.Exists(Server.MapPath("~/images/" + it + ".jpg")))
     {
         return;
     }
     else
     {
         try
         {
             System.Net.WebRequest request = System.Net.WebRequest.Create(Imageurl);
             request.Timeout = 10000;
             System.Net.HttpWebResponse httpresponse = (System.Net.HttpWebResponse)request.GetResponse();
             Stream s = httpresponse.GetResponseStream();
             System.Drawing.Image img = System.Drawing.Image.FromStream(s);
             int towidth  = 135;
             int toheight = 80;
             int x        = 0;
             int y        = 0;
             int ow       = img.Width;
             int oh       = img.Height;
             System.Drawing.Image    bitmap = new System.Drawing.Bitmap(towidth, toheight);
             System.Drawing.Graphics g      = System.Drawing.Graphics.FromImage(bitmap);
             g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
             g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
             g.Clear(System.Drawing.Color.Transparent);
             g.DrawImage(img, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                         new System.Drawing.Rectangle(x, y, ow, oh),
                         System.Drawing.GraphicsUnit.Pixel);
             try
             {
                 bitmap.Save(Server.MapPath("~/images/" + it + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
             }
             catch (System.Exception e)
             {
                 throw e;
             }
             finally
             {
                 img.Dispose();
                 bitmap.Dispose();
                 g.Dispose();
             }
             return;
         }
         catch
         {
             return;
         }
     }
 }
Beispiel #59
0
 public static void GetImageSize(string strAbsolutePath, out int w, out int h)
 {
     try
     {
         System.Drawing.Image img2Scale = System.Drawing.Image.FromFile(strAbsolutePath);
         w = Convert.ToInt32(img2Scale.Width);
         h = Convert.ToInt32(img2Scale.Height);
         img2Scale.Dispose();
     }
     catch (ArgumentException)
     {
         w = 0; h = 0;
     }
 }
Beispiel #60
0
        internal override void Render(IRenderData renderData)
        {
            if (IsNotVisible(renderData))
            {
                return;
            }

            var bounds = GetBounds(renderData.ParentBounds);

            System.Drawing.Image imageData = null;
            try
            {
                imageData = GetImage(renderData.DocumentData, bounds);
                renderData.ElementBounds = GetImageBounds(imageData, bounds);

                if (renderData.IncludeBackground || !IsBackground)
                {
                    using (var image = XImage.FromGdiPlusImage(imageData))
                    {
                        renderData.Graphics.DrawImage(image, renderData.ElementBounds);
                    }
                }
            }
            catch (Exception e)
            {
                var f     = new Font();
                var font  = new XFont(f.GetName(renderData.Section), f.GetSize(renderData.Section) / 1.5, f.GetStyle(renderData.Section));
                var brush = new XSolidBrush(XColor.FromKnownColor(KnownColor.Transparent));
                renderData.Graphics.DrawRectangle(new XPen(f.GetColor(renderData.Section)), brush, bounds);
                var textBrush = new XSolidBrush(XColor.FromArgb(f.GetColor(renderData.Section)));

                try
                {
                    var nextTop = OutputText(renderData, e.Message, font, textBrush, new XPoint(bounds.Left, bounds.Top), bounds.Width);
                    if (e.Data.Contains("source"))
                    {
                        OutputText(renderData, e.Data["source"].ToString(), font, textBrush, new XPoint(bounds.Left, bounds.Top + nextTop), bounds.Width);
                    }
                }
                catch (Exception exception)
                {
                    renderData.Graphics.DrawString(exception.Message, font, brush, new XPoint(bounds.Left, bounds.Top), XStringFormats.TopLeft);
                }
            }
            finally
            {
                imageData?.Dispose();
            }
        }