コード例 #1
0
ファイル: FilmStrip.cs プロジェクト: joelmatton/Worship_Media
        public bool AddPicture(string ImagePath)
        {
            Bitmap bm = new Bitmap(ImagePath);
            Label lb =new Label();

            width=0;height=0;
            folderparts= ImagePath.Split('\\');
            PictureBox pb = new PictureBox();
            pb.Name = pictureBoxNumber .ToString();
            pb.BorderStyle = BorderStyle.FixedSingle;
            height=this.Height-50;
            width = height;//Convert.ToInt32(height*0.70);
            pb.Size = new Size(width,height);
            pb.Location = new Point(pictureBoxOffset,5);
            lb.Text = folderparts[folderparts.GetLength(0)-1];
            lb.Size = new Size(width,15);
            lb.Location = new Point(pictureBoxOffset,height+2);
            pb.SizeMode = PictureBoxSizeMode.CenterImage;
            if(bm.Height>bm.Width)
            {
                pb.Image = (Image)bm.GetThumbnailImage(Convert.ToInt32(((float)height/(float)bm.Height)*bm.Width),height,null,IntPtr.Zero);
            }
            else
            {
                pb.Image = (Image)bm.GetThumbnailImage(width,Convert.ToInt32(((float)width/(float)bm.Width)*bm.Height),null,IntPtr.Zero);
            }
            pb.Click +=new EventHandler(Image_Click);
            pictureBoxOffset = pictureBoxOffset + width + 21;
            this.FilmStripPanel.Controls.Add(pb);
            this.FilmStripPanel.Controls.Add(lb);
            pictureBoxNumber++;
            return true;
        }
コード例 #2
0
 public static Bitmap ResizeBitmap(Bitmap bitmap, Rectangle srcRect, Size newSize)
 {
     if (srcRect.Size.Height <= 0 || srcRect.Size.Width <= 0)
     {
         throw new ArgumentOutOfRangeException("sourceRectangle.Size", srcRect.Size, "sourceRectangle.Size <= (0,0)");
     }
     if (newSize.Height <= 0 || newSize.Width <= 0)
     {
         throw new ArgumentOutOfRangeException("newSize", newSize, "newSize <= (0,0)");
     }
     if (srcRect.Location.IsEmpty && srcRect.Size == bitmap.Size)
     {
         if (srcRect.Size == newSize)
         {
             return new Bitmap(bitmap);
         }
         using (Image image = bitmap.GetThumbnailImage(newSize.Width, newSize.Height, null, IntPtr.Zero))
         {
             return new Bitmap(image);
         }
     }
     using (Bitmap bmp = new Bitmap(srcRect.Width, srcRect.Height, PixelFormat.Format32bppArgb))
     {
         using (Graphics g = Graphics.FromImage(bmp))
         {
             g.Clear(Color.Transparent);
             g.DrawImage(bitmap, new Rectangle(Point.Empty, srcRect.Size), srcRect, GraphicsUnit.Pixel);
         }
         using (Image image = bmp.GetThumbnailImage(newSize.Width, newSize.Height, null, IntPtr.Zero))
         {
             return new Bitmap(image);
         }
     }
 }
コード例 #3
0
 private void GetThumbnail(PaintEventArgs e)
 {
     Image.GetThumbnailImageAbort callback =
         new Image.GetThumbnailImageAbort(ThumbnailCallback);
     if (flag == 1)
     {
         for (int j = 0; j < 4; ++j)
         {
             for (int i = 0; i < 4; ++i)
             {
                 Image image = new Bitmap(filePaths[j * 4 + i]);
                 Image pThumbnail = image.GetThumbnailImage(200, 150, callback, new
                    IntPtr());
                 //label1.Text = filePaths[j*2 +i];
                 e.Graphics.DrawImage(
                    pThumbnail,
                    i * 230 + 20,
                    j * 160 + 10,
                    pThumbnail.Width,
                    pThumbnail.Height);
                 image = null;
                 pThumbnail = null;
                 GC.Collect();
             }
         }
     }
 }
コード例 #4
0
ファイル: ImageLoader.cs プロジェクト: JacquesLucke/Collage
        public Texture2D Load()
        {
            Bitmap bitmap = new Bitmap(fileName);
            Bitmap smallBitmap = null;

            if (maxSize != 0)
            {
                // make the image smaller to need less RAM
                Size newSize;

                float aspectRatio = (float)bitmap.Width / (float)bitmap.Height;
                if (aspectRatio > 1) newSize = new Size(maxSize, (int)Math.Round(maxSize / aspectRatio));
                else newSize = new Size((int)Math.Round(maxSize * aspectRatio), maxSize);

                if(maxSize < 200) smallBitmap = new Bitmap(bitmap.GetThumbnailImage(newSize.Width, newSize.Height, null, IntPtr.Zero));
                else smallBitmap = new Bitmap(bitmap, newSize);

                bitmap.Dispose();
                bitmap = null;
            }

            if (bitmap == null)
            {
                texture = ConvertToTexture(smallBitmap);
                smallBitmap.Dispose();
            }
            else
            {
                texture = ConvertToTexture(bitmap);
                bitmap.Dispose();
            }

            GC.Collect();
            return texture;
        }
コード例 #5
0
		public void Load()
		{
			var files = _root.GetLocalFiles().ToList();

			var titleFile = files.First(file => file.Name == "title.txt");
			Name = File.ReadAllText(titleFile.LocalPath).Trim();

			var toolTipFile = files.FirstOrDefault(file => file.Name == "tip.txt");
			if (toolTipFile != null)
			{
				var tooltipLines = File.ReadAllLines(toolTipFile.LocalPath);
				ToolTipHeader = tooltipLines.ElementAtOrDefault(0)?.Replace("*", "");
				ToolTipBody = tooltipLines.ElementAtOrDefault(1)?.Replace("*", "");
			}

			int tempInt;
			if (Int32.TryParse(Path.GetFileName(_root.LocalPath), out tempInt))
				Order = tempInt;

			LogoFile = files.FirstOrDefault(file => file.Extension == ".png" && !file.Name.Contains("_rbn"));
			if (LogoFile != null)
			{
				Logo = new Bitmap(LogoFile.LocalPath);
				BrowseLogo = Logo.GetThumbnailImage((Logo.Width * 144) / Logo.Height, 144, null, IntPtr.Zero);

				var borderedLogo = Logo.DrawBorder();

				RibbonLogo = borderedLogo.GetThumbnailImage((borderedLogo.Width * 72) / borderedLogo.Height, 72, null, IntPtr.Zero);
				AdBarLogo = borderedLogo.GetThumbnailImage((borderedLogo.Width * 86) / borderedLogo.Height, 86, null, IntPtr.Zero);
			}
			_masterFile = files.FirstOrDefault(file => file.Extension == ".pptx");
		}
コード例 #6
0
 public static Bitmap GetThumbnail(int width, int height, string filter, string caption, ImageFormat format, Image b)
 {
     Bitmap source = new Bitmap(b);
     source = new Bitmap(source.GetThumbnailImage(width, height, null, IntPtr.Zero));
     if (format == ImageFormat.Gif)
     {
         source = new OctreeQuantizer(0xff, 8).Quantize(source);
     }
     if ((filter.Length > 0) && filter.ToUpper().StartsWith("SHARPEN"))
     {
         string str = filter.Remove(0, 7).Trim();
         int nWeight = (str.Length > 0) ? Convert.ToInt32(str) : 11;
         BitmapFilter.Sharpen(source, nWeight);
     }
     if (caption.Length <= 0)
     {
         return source;
     }
     using (Graphics graphics = Graphics.FromImage(source))
     {
         StringFormat format2 = new StringFormat();
         format2.Alignment = StringAlignment.Center;
         format2.LineAlignment = StringAlignment.Center;
         using (Font font = new Font("Arial", 12f))
         {
             graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; 
             graphics.FillRectangle(new SolidBrush(Color.FromArgb(150, 0, 0, 0)), 0, source.Height - 20, source.Width, 20);
             graphics.DrawString(caption, font, Brushes.White, 0f, (float)(source.Height - 20));
             return source;
         }
     }
 }
コード例 #7
0
        public void AddItem(ResourceData tRes, bool froceRegenThumb)
        {
            // 添加缩略图
            // ACHACK [图片资源缩略图创建时机] 在项目文件夹中搜索缩略图,如果没有则创建一个
            String nailFile = Path.Combine(EditorService.Instance.QueryModule<ProjectModule>(null).CurProjDir, "Thumbnail", tRes.ContentId.ToString() + ".ico");
            Image nail = null;
            if (froceRegenThumb || !File.Exists(nailFile))
            {
                Bitmap bmp = new Bitmap(Path.Combine(EditorService.Instance.QueryModule<ProjectModule>(null).CurProjDir, EditorService.Instance.QueryModule<ProjectModule>(null).CurProject.ResourcePath, tRes.ResourceKey));
                nail = bmp.GetThumbnailImage(64, 64, null, new IntPtr());
                nail.Save(nailFile, System.Drawing.Imaging.ImageFormat.Icon);
            }
            else
            {
                nail = new Bitmap(nailFile);
            }
            lsvTexture.LargeImageList.Images.Add(tRes.ContentId.ToString(), nail);
            lsvTexture.SmallImageList.Images.Add(tRes.ContentId.ToString(), nail);

            // 添加到列表
            ListViewItem item = lsvTexture.Items.Add(tRes.ResourceKey);     // NOTE 在此视图中,显示的图片取自Resource
            item.ImageKey = tRes.ContentId.ToString();
            item.SubItems.Add(tRes.ContentId.ToString());
            item.SubItems.Add(tRes.ContentKey);
            item.SubItems.Add(tRes.ResourceKey);
            item.SubItems.Add(tRes.Processor);
            item.SubItems.Add(tRes.Argument);
        }
コード例 #8
0
ファイル: Browser.cs プロジェクト: Zerq/InventorySystem
        public void SaveTumb(string reference, ImageList imageList)
        {
            this.Url = $@"https://www.google.se/search?q=product+search&ie=utf-8&oe=utf-8&client=firefox-b&gfe_rd=cr&ei=pJCtV_-sHOzk8AfgsISoDw#q={reference}";
            if (this.ShowDialog() == DialogResult.OK) {
                var format = IsImage(this.Url);

                if (format!=null) {
                    WebClient client = new WebClient();
                    var data = client.DownloadData(this.Url);

                    var index = this.Url.LastIndexOf(".");
                    var extension = this.Url.Substring(index).ToLower();

                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(data)) {
                        System.Drawing.Image bmp = new Bitmap(stream);
                        var image = bmp.GetThumbnailImage(32, 32, callbackAbort, IntPtr.Zero);
                        image.Save($"{AppDomain.CurrentDomain.BaseDirectory}Images/{reference}.png", format);

                        imageList.Images.RemoveByKey(reference);
                        imageList.Images.Add(reference, image);

                    }

                }
            }
        }
コード例 #9
0
        private Bitmap scaleBitmap(Bitmap bmp, PictureBox picBox)
        {
            float ratio = 1.0f;
            int thumbHeight = 0;
            int thumbWidth = 0;

            if (bmp.Height > picBox.Height || bmp.Width > picBox.Width)
            {
                Image.GetThumbnailImageAbort myCallback =
                    new Image.GetThumbnailImageAbort(ThumbnailCallback);

                if (bmp.Height >= bmp.Width)
                {
                    ratio = (((float)bmp.Width) / ((float)bmp.Height));
                    thumbHeight = picBox.Height;
                    thumbWidth = (int)((thumbHeight) * (ratio));
                }
                else
                {
                    ratio = (((float)bmp.Height) / ((float)bmp.Width));
                    thumbWidth = picBox.Width;
                    thumbHeight = (int)((thumbWidth) * (ratio));
                }

                Image myThumbnail = bmp.GetThumbnailImage(thumbWidth, thumbHeight, myCallback, IntPtr.Zero);
                return new Bitmap(myThumbnail);
            }
            return bmp;
        }
コード例 #10
0
        public void GenerateThumbnail(Stream imgFileStream, Stream thumbStream)
        {
            Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Bitmap bitmap = new Bitmap(imgFileStream);
            int thumbWidth = MaxThumbWidth;
            int thumbHeight = MaxThumbHeight;
            if (bitmap.Width > bitmap.Height)
            {
                thumbHeight = Decimal.ToInt32(((Decimal)bitmap.Height / bitmap.Width) * thumbWidth);
                if (thumbHeight > MaxThumbHeight)
                {
                    thumbHeight = MaxThumbHeight;
                }
            }
            else
            {
                thumbWidth = Decimal.ToInt32(((Decimal)bitmap.Width / bitmap.Height) * thumbHeight);
                if (thumbWidth > MaxThumbWidth)
                {
                    thumbWidth = MaxThumbWidth;
                }
            }

            Image thumbnail = bitmap.GetThumbnailImage(thumbWidth, thumbHeight, callback, IntPtr.Zero);

            thumbnail.Save(thumbStream,ImageFormat.Jpeg);
        }
コード例 #11
0
 public ActionResult Thumbnail(string path)
 {
     var myCallback =
         new Image.GetThumbnailImageAbort(ThumbnailCallback);
     var paths = new List<string>(2);
     BuildPath(path, out folderPath, out resourcePath);
     var folder = session.OpenFolder(folderPath + "/");
     var resource = folder.GetResource(resourcePath + "/");
     var sourceStream = resource.GetReadStream();
     Bitmap bitmap = null;
     try
     {
         bitmap = new Bitmap(sourceStream);
     }
     catch (Exception)
     {
         var fs = new FileStream(Server.MapPath("~/Content/kendo/2014.2.716/Bootstrap/imagebrowser.png"), FileMode.Open);
         var tempBs = new byte[fs.Length];
         fs.Read(tempBs, 0, tempBs.Length);
         return new FileContentResult(tempBs, "image/jpeg");
     }
     var myThumbnail = bitmap.GetThumbnailImage(84, 70, myCallback, IntPtr.Zero);
     var ms = new MemoryStream();
     var myEncoderParameters = new EncoderParameters(1);
     var myEncoderParameter = new EncoderParameter(Encoder.Quality, 25L);
     myEncoderParameters.Param[0] = myEncoderParameter;
     myThumbnail.Save(ms, GetEncoderInfo("image/jpeg"), myEncoderParameters);
     ms.Position = 0;
     var bytes = ms.ToArray();
     return new FileContentResult(bytes, "image/jpeg");
 }
コード例 #12
0
ファイル: OracleImageReader.cs プロジェクト: mparsin/Elements
        /// <summary>
        /// Reads the image.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="ordinalPosition">The ordinal position.</param>
        /// <param name="generateThumbnail">if set to <c>true</c> [generate thumbnail].</param>
        /// <returns>System.Byte[][].</returns>
        public static byte[] ReadImage(IDataReader reader, int ordinalPosition, bool generateThumbnail = false)
        {
            if (reader == null)
                return null;

            if (string.IsNullOrEmpty(reader.GetValue(ordinalPosition).ToString()))
                return new byte[] { };

            var blob = ((OracleDataReader)reader).GetOracleBlob(ordinalPosition);

            var byteArr = new byte[blob.Length];

            blob.Read(byteArr, 0, Convert.ToInt32(blob.Length));

            using (var stream = new MemoryStream(byteArr))
            {
                var retVal = stream.ToArray();

                if (generateThumbnail && stream.Length > 0)
                {
                    var bitmap = new Bitmap(stream);
                    var image = bitmap.GetThumbnailImage(50, 50, AdoHelper.ThumbnailCallback, IntPtr.Zero);

                    using (var ms = new MemoryStream())
                    {
                        image.Save(ms, ImageFormat.Png);
                        return ms.ToArray();
                    }
                }

                return retVal;
            }
        }
コード例 #13
0
        public static Bitmap GetThumbnail(Bitmap bmpImage, Size size)
        {
            double width = bmpImage.Width;
             double height = bmpImage.Height;

             Double xFactor = new Double();
             Double yFactor = new Double();
             xFactor = (double)size.Width / width;
             yFactor = (double)size.Height / height;

             Double scaleFactor = Math.Min(xFactor, yFactor);

             Size scaledSize = new Size();
             scaledSize.Width = Convert.ToInt32(width * scaleFactor);
             scaledSize.Height = Convert.ToInt32(height * scaleFactor);

             Bitmap scaledOriginal = (Bitmap) bmpImage.GetThumbnailImage(scaledSize.Width, scaledSize.Height, new Image.GetThumbnailImageAbort(target), IntPtr.Zero);
             Bitmap thumnailBmp = new Bitmap(size.Width, size.Height);

             for (int y = 0; y < thumnailBmp.Height; y++)
             {
            for (int x = 0; x < thumnailBmp.Width; x++)
            {
               if ((x < scaledOriginal.Width) && (y < scaledOriginal.Height))
               {
                  thumnailBmp.SetPixel(x, y, scaledOriginal.GetPixel(x, y));
               }
               else
               {
                  thumnailBmp.SetPixel(x, y, Color.Transparent);
               }
            }
             }
             return thumnailBmp;
        }
コード例 #14
0
    /// <summary>
    /// Initialize a new instance of the class.
    /// </summary>
    /// <param name="fileName"></param>
    public EmpSymbol(string fileName)
    {
        Syncfusion.Windows.Forms.Diagram.Rectangle groupRect = new Syncfusion.Windows.Forms.Diagram.Rectangle(0, 0, 255, 75);
        groupRect.Name                  = "Rectangle";
        groupRect.FillStyle.Type        = FillStyleType.LinearGradient;
        groupRect.FillStyle.ForeColor   = Color.White;
        groupRect.FillStyle.Color       = System.Drawing.Color.FromArgb(240, 242, 240);
        groupRect.LineStyle.LineColor   = Color.Black;
        groupRect.LineStyle.LineWidth   = 1;
        groupRect.EditStyle.AllowSelect = false;
        this.AppendChild(groupRect);

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(fileName);
        System.Drawing.Image  Image  = bitmap.GetThumbnailImage(60, 50, null, IntPtr.Zero);
        bitmap = new System.Drawing.Bitmap(Image);

        BitmapNode bitmapNode = new BitmapNode(bitmap);

        bitmapNode.PinPoint              = new PointF(bitmapNode.PinPoint.X + 10, bitmapNode.PinPoint.Y + 10);
        bitmapNode.LineStyle.LineColor   = Color.Transparent;
        bitmapNode.EditStyle.AllowSelect = false;
        this.AppendChild(bitmapNode);

        txtNode.PinPoint            = new PointF(bitmapNode.PinPoint.X + 40, bitmapNode.PinPoint.Y - 30);
        txtNode.LineStyle.LineColor = Color.Transparent;
        txtNode.FontStyle.Size      = 9;
        txtNode.FontStyle.Family    = "Arial";

        txtNode.SizeToText(new SizeF(130, 100));
        this.AppendChild(txtNode);
        BackgroundShapeType = BackgroundShape.ellipse;
        SymbolShapeType     = SymbolShape.RightDownTriangle;
    }
コード例 #15
0
 public Image SizeScaling(Bitmap image, int width, int height, bool distorted)
 {
     try
     {
         double realRatio = ((double) image.Height)/((double) image.Width);
         if (width != 0 & height != 0)
         {
             if (distorted) return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero);
             var heightAfterRatio = (int) Math.Floor(realRatio*width);
             var widthAfterRatio = (int) Math.Floor(height/realRatio);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Tiff);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(widthAfterRatio, heightAfterRatio, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(widthAfterRatio, heightAfterRatio, ThumbnailCallback, IntPtr.Zero);
         }
         if (width != 0)
         {
             var heightAfterRatio = (int) Math.Floor(realRatio*width);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Jpeg);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(width, heightAfterRatio, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(width, heightAfterRatio, ThumbnailCallback, IntPtr.Zero);
         }
         if (height != 0)
         {
             var widthAfterRatio = (int) Math.Floor(height/realRatio);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Jpeg);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(widthAfterRatio, height, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(widthAfterRatio, height, ThumbnailCallback, IntPtr.Zero);
         }
         return image;
     }
     catch (Exception ex)
     {
         return image;
     }
 }
コード例 #16
0
        public void Example_GetThumb(PaintEventArgs e)
        {
            Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            Bitmap myBitmap = new Bitmap("Climber.jpg");
            Image myThumbnail = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero);

            e.Graphics.DrawImage(myThumbnail, 150, 75);
        }
コード例 #17
0
        Image LeerImagen(string codigo)
        {
            string archivo = Application.StartupPath + "\\Imagenes\\" + codigo + ".jpg";

            System.Drawing.Bitmap imagen = new System.Drawing.Bitmap((Image)Image.FromFile(
                                                                         Application.StartupPath + "\\Imagenes\\" + codigo + ".jpg"));
            return(imagen.GetThumbnailImage(40, 40, null, IntPtr.Zero));
        }
コード例 #18
0
        /// <summary>
        /// Create Icon
        /// </summary>
        /// <param name="sourceBitmap">Set source Bitmap</param>
        /// <param name="iconSize">Set icon size</param>
        /// <returns></returns>
        public static Icon CreateIcon(this System.Drawing.Bitmap sourceBitmap, IconSizeDimensions iconSize)
        {
            System.Drawing.Bitmap squareCanvas = sourceBitmap.CopyToSquareCanvas(Color.Transparent);
            squareCanvas = (System.Drawing.Bitmap)squareCanvas.GetThumbnailImage((int)iconSize, (int)iconSize, null, new IntPtr());

            Icon iconResult = Icon.FromHandle(squareCanvas.GetHicon());

            return(iconResult);
        }
コード例 #19
0
 private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
 {
     WebBrowser m_WebBrowser = (WebBrowser)sender;
     m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
     m_WebBrowser.ScrollBarsEnabled = false;
     m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
     m_WebBrowser.BringToFront();
     m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
     m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
 }
コード例 #20
0
        public static Image BitmapToThumbnail(System.Drawing.Bitmap bitmap)
        {
            using (Stream BitmapStream = System.IO.File.Open("", System.IO.FileMode.Open))
            {
                Image img = Image.FromStream(BitmapStream);

                var bmp       = new System.Drawing.Bitmap(img);
                var thumbnail = bmp.GetThumbnailImage(100, 100, null, IntPtr.Zero);
                return(thumbnail);
            }
        }
コード例 #21
0
        protected System.Drawing.Image InitImage(string HCC_FILE_PDF, string path, int dWidth = 0, int dHeight = 0)
        {
            var urlImage = Path.Combine(HCC_FILE_PDF, path);

            byte[] ImageData = System.IO.File.ReadAllBytes(urlImage);

            System.Drawing.Image img = new System.Drawing.Bitmap(urlImage);

            if (dWidth > 0 && dHeight > 0)
            {
                return(img.GetThumbnailImage(dWidth, dHeight, null, IntPtr.Zero));
            }
            var res = img.GetThumbnailImage(255, 115, null, IntPtr.Zero);

            img.Dispose();
            return(res);
            //System.Drawing.Size thumbnailSize = GetThumbnailSize(img);
            //System.Drawing.Image thumbnail = img.GetThumbnailImage(thumbnailSize.Width, thumbnailSize.Height, null, IntPtr.Zero);
            //return thumbnail;
        }
コード例 #22
0
ファイル: image.cs プロジェクト: ratsil/bethe.helpers
		public void ProcessRequest(HttpContext context)
		{
            try
            {
                if (null == HttpContext.Current.Request.Params["name"])
                    throw new Exception("wrong request");
                string sCaptchaName = HttpContext.Current.Request.Params["name"];
                int nSourceMatWidth = 800, nSourceMatHeight = 600, nSourceDigitWidth = 120, nSourceDigitHeight = 120, nTargetWidth = 610, nTargetHeight = 180, nRotateSafe = 50, nDigitSpace = 7;
                string sCode = "";
                Random cRandom = new Random((DateTime.Now.Ticks.ToString() + HttpContext.Current.Session.SessionID).GetHashCode());
                context.Response.ContentType = "image/jpeg";
                Bitmap cBitmap = new Bitmap(nTargetWidth, nTargetHeight);
                Graphics cGraphics = Graphics.FromImage(cBitmap);
                cGraphics.RotateTransform(cRandom.Next(-5, 6));
                cGraphics.DrawImage(Resources.mat,
                    new Point(
                        cRandom.Next((nTargetWidth + nRotateSafe) - nSourceMatWidth, -1 * nRotateSafe),
                        cRandom.Next((nTargetHeight + nRotateSafe) - nSourceMatHeight, -1 * nRotateSafe)
                    )
                );

                int nDigit = 0;
                for (int nIndx = 0; 4 > nIndx; nIndx++)
                {
                    nDigit = cRandom.Next(0, 10);
                    sCode += nDigit;
                    cGraphics.ResetTransform();
                    cGraphics.TranslateTransform(50 + (nIndx * (nSourceDigitWidth + nDigitSpace)), nRotateSafe);
                    cGraphics.RotateTransform((float)cRandom.Next(-300, 300) / 10);
                    cGraphics.DrawImage((Bitmap)Resources.ResourceManager.GetObject("_" + nDigit), new Point(0, 0));
                }
                HttpContext.Current.Session["captcha_code:" + sCaptchaName] = (sCode + HttpContext.Current.Session.SessionID).GetHashCode();
                HttpContext.Current.Session["captcha_expire:" + sCaptchaName] = DateTime.Now.AddSeconds(60);

                ImageCodecInfo cImageCodecInfo = null;
                foreach (ImageCodecInfo cICI in ImageCodecInfo.GetImageEncoders())
                {
                    if (ImageFormat.Jpeg.Guid == cICI.FormatID)
                    {
                        cImageCodecInfo = cICI;
                        break;
                    }
                }
                if (null == cImageCodecInfo)
                    throw new Exception("can't find jpeg codec");
                EncoderParameters cEncoderParameters = new EncoderParameters(1);
                cEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 75L);
                cBitmap.GetThumbnailImage(170, 50, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero).Save(context.Response.OutputStream, cImageCodecInfo, cEncoderParameters);
                cBitmap.Dispose();
            }
            catch { }
		}
コード例 #23
0
ファイル: FileHelper.cs プロジェクト: eternalwt/CMS
 //For image thumbnial
 public static void CreateThumbNail(string sourceFileName, string destinationFileName, int width, int height)
 {
     try {
         Image thumb;
         Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
         if (System.IO.File.Exists(sourceFileName)) {
             string imgname = System.IO.Path.GetFileName(sourceFileName);
             string extension = System.IO.Path.GetExtension(sourceFileName).ToLower();
             ImageFormat imageFormat = null;
             switch (extension) {
                 case ".jpg":
                     imageFormat = ImageFormat.Jpeg;
                     break;
                 case ".jpeg":
                     imageFormat = ImageFormat.Jpeg;
                     break;
                 case ".bmp":
                     imageFormat = ImageFormat.Bmp;
                     break;
                 case ".emf":
                     imageFormat = ImageFormat.Emf;
                     break;
                 case ".exif":
                     imageFormat = ImageFormat.Exif;
                     break;
                 case ".gif":
                     imageFormat = ImageFormat.Gif;
                     break;
                 case ".ico":
                     imageFormat = ImageFormat.Icon;
                     break;
                 case ".png":
                     imageFormat = ImageFormat.Png;
                     break;
                 case ".tiff":
                     imageFormat = ImageFormat.Tiff;
                     break;
                 case ".wmf":
                     imageFormat = ImageFormat.Wmf;
                     break;
             }
             if (imageFormat != null) {
                 System.Drawing.Image imagesize = System.Drawing.Image.FromFile(sourceFileName);
                 Bitmap bitmapNew = new Bitmap(imagesize);
                 thumb = bitmapNew.GetThumbnailImage(width, height, null, IntPtr.Zero);
                 //Save image in TumbnailImage folder
                 thumb.Save(destinationFileName, imageFormat);
             }
         }
     } catch { }
 }
コード例 #24
0
ファイル: MainForm.cs プロジェクト: Download/Irrlicht-Lime
		private void addImageToParticleList(string f, bool makeThisImageSelected)
		{
			Image i = new Bitmap(f);

			ParticleInfo p = new ParticleInfo();
			p.FileName = f;
			p.Preview = i.GetThumbnailImage(128, 128, null, IntPtr.Zero);
			p.DisplayName = Path.GetFileName(f) + " (" + i.Width + "x" + i.Height + ")";

			int s = listBoxParticleList.Items.Add(p);

			if (makeThisImageSelected)
				listBoxParticleList.SelectedIndex = s;
		}
コード例 #25
0
ファイル: Theme.cs プロジェクト: w01f/VolgaTeam.Dashboard
		public void Load()
		{
			var files = _root.GetLocalFiles().ToList();

			var titleFile = files.First(file => file.Name == "title.txt");
			Name = File.ReadAllText(titleFile.LocalPath).Trim();

			int tempInt;
			if (Int32.TryParse(Path.GetFileName(_root.LocalPath), out tempInt))
				Order = tempInt;

			var bigLogoFile = files.FirstOrDefault(file => file.Name == "preview.png");
			if (bigLogoFile != null)
			{
				Logo = new Bitmap(bigLogoFile.LocalPath);
				BrowseLogo = Logo.GetThumbnailImage(Logo.Width * 144 / Logo.Height, 144, null, IntPtr.Zero);
				var ribbonLogo = Logo.GetThumbnailImage(Logo.Width * 72 / Logo.Height, 72, null, IntPtr.Zero);
				RibbonLogo = ribbonLogo.DrawBorder();
			}

			_themeFile = files.FirstOrDefault(file => file.Extension == ".thmx");

			ApprovedSlides = new List<SlideType>();
		}
コード例 #26
0
ファイル: Form1.cs プロジェクト: xs2ranjeet/13ns9-1spr
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Jpeg Files (*.jpg)|*.jpg|All Files (*.*)|*.*";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                try
                {

                    Bitmap myBmp = new Bitmap(dlg.FileName);

                    Image.GetThumbnailImageAbort myCallBack = new Image.GetThumbnailImageAbort(ThumbnailCallBack);
                    Image imgPreview = myBmp.GetThumbnailImage(200, 200, myCallBack, IntPtr.Zero);

                    MemoryStream ms = new MemoryStream();
                    imgPreview.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);

                    BinaryReader br=new BinaryReader(ms);

                    byte[] image = br.ReadBytes((int)ms.Length);

                    SqlCommand comm = new SqlCommand();
                    comm.Connection = conn;
                    comm.CommandText = @"INSERT INTO tbImages (Path, ImgPreView) VALUES (@Path, @Image)";
                    comm.Parameters.Add("@Path", SqlDbType.NChar, 260).Value = dlg.FileName;
                    comm.Parameters.Add("@Image", SqlDbType.Image, image.Length).Value = image;

                    comm.ExecuteNonQuery();

                    ms.Close();             

                   
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally 
                {
                   

                }
            }
        }
コード例 #27
0
ファイル: MainWindow.xaml.cs プロジェクト: KarimLUCCIN/JNUI
        private void BrowserScreenshot(System.Windows.Controls.Image ongletImage)
        {
            Rect bounds = VisualTreeHelper.GetDescendantBounds(currentWb);
            Bitmap image = new Bitmap((int)bounds.Width, (int)bounds.Height);
            ControlExtensions.DrawToBitmap(currentWb, image, bounds);

            System.Drawing.Image thumb = image.GetThumbnailImage((int)ongletImage.Width, (int)ongletImage.Height, null, IntPtr.Zero);

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            MemoryStream ms = new MemoryStream();
            thumb.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);
            bi.StreamSource = ms;
            bi.EndInit();
            ongletImage.Source = bi;
        }
コード例 #28
0
ファイル: ImageHelper.cs プロジェクト: jakforest/WCFImage
 public static byte[] GetThumbnail(this byte[] imageBytes, int width, int height)
 {
     try
     {
         using (MemoryStream streamInput = new MemoryStream(imageBytes))
         {
             System.Drawing.Image image = new Bitmap(streamInput);
             System.Drawing.Image.GetThumbnailImageAbort deleg = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
             System.Drawing.Image thumbnail = image.GetThumbnailImage(width, height, deleg, IntPtr.Zero);
             byte[] result = thumbnail.GetBytes(image.RawFormat);
             return result;
         }
     }
     catch (Exception ex)
     {
         return imageBytes;
     }
 }
コード例 #29
0
        void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Cancelled == false && e.Error == null) {
                try {
                    using (Bitmap bm = new Bitmap(new MemoryStream(e.Result))) {
                        device.UpdateBitmap(bm.GetThumbnailImage(320, 240, null, IntPtr.Zero) as Bitmap, Priority.Normal);
                    }
                }
                catch {
                    // shitty image, too bad
                }
            }

            // schedule next image refresh in 3 seconds
            scheduler = new System.Threading.Timer(delegate(object s) {
                RefreshImage();
            }, null, new TimeSpan(30000000), new TimeSpan(-1));
        }
コード例 #30
0
ファイル: frmMain.cs プロジェクト: rainssong/IconBuilder
 /// <summary>
 /// 获取等比例缩放图片的方法
 /// </summary>
 /// <param name="imgPath">待缩放图片路径</param>
 /// <param name="savePath">缩放图片保存路径</param>
 /// <param name="format">缩放图片保存的格式</param>
 /// <param name="scaling">要保持的宽度或高度</param>
 /// <returns></returns>
 public bool GetThumbnail(string imgPath, string savePath, ImageFormat format, int scaling)
 {
     try
     {
         using (Bitmap myBitmap = new Bitmap(imgPath))
         {
             using (Image myThumbnail = myBitmap.GetThumbnailImage(scaling, scaling, () => { return false; }, IntPtr.Zero))
             {
                 myThumbnail.Save(savePath, format);
             }
         }
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #31
0
        protected override void DoInitialize()
        {
            base.DoInitialize();

            {
                Bitmap bitmap = new System.Drawing.Bitmap(this.textureFilename);
                if (bitmap.Width != 512 || bitmap.Height != 512)
                {
                    bitmap = (Bitmap)bitmap.GetThumbnailImage(512, 512, null, IntPtr.Zero);
                }
                /* We require 1 byte alignment when uploading texture data */
                //GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
                /* Clamping to edges is important to prevent artifacts when scaling */
                /* Linear filtering usually looks best for text */
                var texture = new Texture(TextureTarget.Texture2D,
                                          new BitmapFiller(bitmap, 0, OpenGL.GL_RGBA32F, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE),
                                          new SamplerParameters(
                                              TextureWrapping.ClampToEdge,
                                              TextureWrapping.ClampToEdge,
                                              TextureWrapping.ClampToEdge,
                                              TextureFilter.Linear,
                                              TextureFilter.Linear));
                texture.Initialize();
                bitmap.Dispose();
                this.inputTexture = texture;
            }
            {
                var texture = new Texture(TextureTarget.Texture2D,
                                          new TexStorage2DImageFiller(8, OpenGL.GL_RGBA32F, 512, 512),
                                          new NullSampler());
                texture.Initialize();
                this.intermediateTexture = texture;
            }
            {
                // This is the texture that the compute program will write into
                var texture = new Texture(TextureTarget.Texture2D,
                                          new TexStorage2DImageFiller(8, OpenGL.GL_RGBA32F, 512, 512),
                                          new NullSampler());
                texture.Initialize();
                this.outputTexture = texture;
            }

            this.SetUniform("output_image", this.outputTexture);
        }
コード例 #32
0
ファイル: ImageHelper.cs プロジェクト: macki/Pracownice
        public static Image CreateThumbnails(string inputFile)
        {
            Image pThumbnail = null;

            try
            {
                Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                Image image = new Bitmap(inputFile);

                //TODO Resize function
                pThumbnail = image.GetThumbnailImage(100, 150, callback, new IntPtr());
            }
            catch (Exception e)
            {
                return pThumbnail;
            }

            return pThumbnail;
        }
コード例 #33
0
ファイル: MenuForm.cs プロジェクト: hpinio/BMResto_v1.0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Filter = "Image File(*.jpg; *.jpeg; *.gif; *.bmp) | *.jpg; * .jpeg; *.gif; *.bmp";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    Bitmap image = new Bitmap(open.FileName);
                    Image thumbnail = image.GetThumbnailImage(114, 114, null, new IntPtr());
                    pbMenuImage.Image = thumbnail;
                    txtImagePath.Text = open.FileName;
                }

            }
            catch (Exception)
            {
                throw new ApplicationException("Failed loading image");
            }
        }
コード例 #34
0
ファイル: CliForm.cs プロジェクト: ngaspar/ScrCap
        private static void capture(Object sender, EventArgs e)
        {
            if (sendSocket != null && sendSocket.Connected)
            {
                bmp = CaptureScreen.GetDesktopImage();
                if(scale != 1)
                    bmp = (Bitmap)bmp.GetThumbnailImage((int)(bmp.Width * scale), (int)(bmp.Height * scale), null, System.IntPtr.Zero);

                if (ms != null && (ms.CanRead || ms.CanWrite))
                    ms.Close();
                ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                if (!sendToSocket(ms.ToArray()))
                    sendSocket.Disconnect(true);
            }
            else
            {
                connect();
            }
        }
コード例 #35
0
ファイル: Main.cs プロジェクト: koush/shrinkimage
        public static void Main(string[] args)
        {
            string input;
            string output;
            float scale;

            if (args.Length == 3)
            {
                input = args[1];
                output = args[2];
            }
            else if (args.Length == 2)
            {
                input = output = args[1];
            }
            else
            {
                Console.WriteLine("shrinkimage percent%|max_dimension input [output]");
                return;
            }

            Bitmap bitmap = new Bitmap(input);
            if (args[0].EndsWith("%"))
            {
                scale = float.Parse(args[0].Trim('%')) / 100;
            }
            else
            {
                int maxdim = int.Parse(args[0]);
                int bitmapMax = Math.Max(bitmap.Width, bitmap.Height);
                if (bitmapMax > maxdim)
                    scale = (float)maxdim / (float)bitmapMax;
                else
                    scale = 1;
            }

            Bitmap outputBitmap  = new Bitmap(bitmap.GetThumbnailImage((int)(scale * bitmap.Width), (int)(scale * bitmap.Height), null, IntPtr.Zero));
            outputBitmap.Save(output);
        }
コード例 #36
0
        public ActionResult Upload(HttpPostedFileBase[] file1)
        {
            foreach (var file in file1)
            {
                if (file.ContentLength < 0)
                    continue;

                string appPath = HttpContext.Request.PhysicalApplicationPath;
                string savaFolder = @"\Images\" + 1 + @"\" + 1 + @"\Temp\";
                string saveDir = appPath + savaFolder;

                string ext = file.FileName.Substring(file.FileName.LastIndexOf("."));
                string newFileName = string.Format("{0}-{1}-{2}-{3}-{4}{5}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Minute, DateTime.Now.Millisecond, ext);

                string fileUrl = saveDir + newFileName;

                Directory.CreateDirectory(saveDir);
                file.SaveAs(fileUrl);

                Image.GetThumbnailImageAbort callBack =new Image.GetThumbnailImageAbort(ThumbnailCallback);

                Bitmap image = new Bitmap(fileUrl);
                int[] thumbnailScale = getThumbnailImageScale(1280, 1280, image.Width, image.Height);
                Image smallImage = image.GetThumbnailImage(thumbnailScale[0], thumbnailScale[1], callBack, IntPtr.Zero);

                string savaFolder2 = @"\Images2\" + 1 + @"\" + 1 + @"\Temp\";
                string saveDir2 = appPath + savaFolder2;

                string newFileName2 = string.Format("{0}-{1}-{2}-{3}-{4}{5}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Minute, DateTime.Now.Millisecond, ext);

                string fileUrl2 = saveDir2 + newFileName2;

                Directory.CreateDirectory(saveDir2);
                smallImage.Save(fileUrl2);

            }

            return View();
        }
コード例 #37
0
        private void InitTexture()
        {
            System.Drawing.Bitmap contentBitmap = ManifestResourceLoader.LoadBitmap("DemoSimplePointSpriteElement.png");

            // step 4: get texture's size
            int targetTextureWidth;

            {
                //	Get the maximum texture size supported by OpenGL.
                int[] textureMaxSize = { 0 };
                GL.GetInteger(GetTarget.MaxTextureSize, textureMaxSize);

                //	Find the target width and height sizes, which is just the highest
                //	posible power of two that'll fit into the image.

                targetTextureWidth = textureMaxSize[0];

                int scaledWidth = contentBitmap.Width;

                for (int size = 1; size <= textureMaxSize[0]; size *= 2)
                {
                    if (scaledWidth < size)
                    {
                        targetTextureWidth = size / 2;
                        break;
                    }
                    if (scaledWidth == size)
                    {
                        targetTextureWidth = size;
                    }
                }
            }

            // step 5: scale contentBitmap to right size
            System.Drawing.Bitmap targetImage = contentBitmap;
            if (contentBitmap.Width != targetTextureWidth || contentBitmap.Height != targetTextureWidth)
            {
                //  Resize the image.
                targetImage = (System.Drawing.Bitmap)contentBitmap.GetThumbnailImage(targetTextureWidth, targetTextureWidth, null, IntPtr.Zero);
            }

            // step 6: generate texture
            {
                //  Lock the image bits (so that we can pass them to OGL).
                BitmapData bitmapData = targetImage.LockBits(new Rectangle(0, 0, targetImage.Width, targetImage.Height),
                                                             ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                //GL.ActiveTexture(GL.GL_TEXTURE0);
                GL.GenTextures(1, texture);
                GL.BindTexture(GL.GL_TEXTURE_2D, texture[0]);
                GL.TexImage2D(GL.GL_TEXTURE_2D, 0, (int)GL.GL_RGBA,
                              targetImage.Width, targetImage.Height, 0, GL.GL_BGRA, GL.GL_UNSIGNED_BYTE,
                              bitmapData.Scan0);
                //  Unlock the image.
                targetImage.UnlockBits(bitmapData);
                /* We require 1 byte alignment when uploading texture data */
                //GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
                /* Clamping to edges is important to prevent artifacts when scaling */
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, (int)GL.GL_CLAMP_TO_EDGE);
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, (int)GL.GL_CLAMP_TO_EDGE);
                /* Linear filtering usually looks best for text */
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR);
                GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR);
            }

            // step 7: release images
            {
                //targetImage.Save("PointSpriteFontElement-TargetImage.png");
                if (targetImage != contentBitmap)
                {
                    targetImage.Dispose();
                }

                contentBitmap.Dispose();
            }
        }
コード例 #38
0
    private void SaveBannerContent(int BannerId, int ImageId)
    {
        try
        {
            SageBannerInfo obj = new SageBannerInfo();

            if (Session["EditImageID"] != null && Session["EditImageID"].ToString() != string.Empty)
            {
                obj.ImageID = Int32.Parse(Session["EditImageID"].ToString());
                if (fuFileUpload.HasFile)
                {
                    obj.ImagePath       = fuFileUpload.FileName.Replace(" ", "_");
                    obj.NavigationImage = fuFileUpload.FileName.Replace(" ", "_");
                }
                else
                {
                    obj.ImagePath       = Convert.ToString(Session["ImageName"]);
                    obj.NavigationImage = Convert.ToString(Session["ImageName"]);
                }
            }
            else
            {
                obj.ImageID         = 0;
                obj.ImagePath       = fuFileUpload.FileName.Replace(" ", "_");
                obj.NavigationImage = fuFileUpload.FileName.Replace(" ", "_");
            }
            obj.Caption = "";
            if (rdbReadMorePageType.SelectedItem.Text == "Page")
            {
                obj.ReadMorePage = ddlPagesLoad.SelectedValue.ToString();
                obj.LinkToImage  = string.Empty;
            }
            if (rdbReadMorePageType.SelectedItem.Text == "Web Url")
            {
                obj.LinkToImage  = txtWebUrl.Text;
                obj.ReadMorePage = string.Empty;
            }
            obj.UserModuleID   = Int32.Parse(SageUserModuleID);
            obj.BannerID       = BannerId;
            obj.ImageID        = ImageId;
            obj.ReadButtonText = txtReadButtonText.Text;
            obj.Description    = txtBannerDescriptionToBeShown.Value.Trim();
            obj.PortalID       = GetPortalID;


            string swfExt = System.IO.Path.GetExtension(fuFileUpload.PostedFile.FileName);
            if (swfExt == ".swf")
            {
                if (fuFileUpload.FileContent.Length > 0)
                {
                    string        Path           = GetUplaodImagePhysicalPath();
                    DirectoryInfo dirUploadImage = new DirectoryInfo(Path);
                    if (dirUploadImage.Exists == false)
                    {
                        dirUploadImage.Create();
                    }
                    string fileUrl = Path + fuFileUpload.PostedFile.FileName;
                    fuFileUpload.PostedFile.SaveAs(fileUrl);
                    swfFileName = "Modules/Sage_Banner/images/" + fuFileUpload.PostedFile.FileName;
                }
            }
            else
            {
                string target          = Server.MapPath("~/Modules/Sage_Banner/images/OriginalImage");
                string CropImageTarget = Server.MapPath("~/Modules/Sage_banner/images/CroppedImages");
                string thumbTarget     = Server.MapPath("~/Modules/Sage_Banner/images/ThumbNail");
                if (!Directory.Exists(target))
                {
                    Directory.CreateDirectory(target);
                }
                if (!Directory.Exists(CropImageTarget))
                {
                    Directory.CreateDirectory(CropImageTarget);
                }
                if (!Directory.Exists(thumbTarget))
                {
                    Directory.CreateDirectory(thumbTarget);
                }
                System.Drawing.Image.GetThumbnailImageAbort thumbnailImageAbortDelegate = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                if (fuFileUpload.HasFile)
                {
                    fuFileUpload.SaveAs(System.IO.Path.Combine(target, fuFileUpload.FileName.Replace(" ", "_")));
                    fuFileUpload.SaveAs(System.IO.Path.Combine(CropImageTarget, fuFileUpload.FileName.Replace(" ", "_")));
                    using (System.Drawing.Bitmap originalImage = new System.Drawing.Bitmap(fuFileUpload.PostedFile.InputStream))
                    {
                        using (System.Drawing.Image thumbnail = originalImage.GetThumbnailImage(80, 80, thumbnailImageAbortDelegate, IntPtr.Zero))
                        {
                            thumbnail.Save(System.IO.Path.Combine(thumbTarget, fuFileUpload.FileName.Replace(" ", "_")));
                        }
                    }
                }
            }
            SageBannerController objcont = new SageBannerController();
            objcont.SaveBannerContent(obj);
            ShowMessage(SageMessageTitle.Information.ToString(), SageMessage.GetSageModuleLocalMessageByVertualPath("Modules/Sage_Banner/ModuleLocalText", "BannerSavedsuccesfully"), "", SageMessageType.Success);
            Session["ImageName"]   = null;
            Session["EditImageID"] = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
コード例 #39
0
 public Drawing.Bitmap GetImage(string imageName)
 {
     Drawing.Bitmap bmp = (Drawing.Bitmap)Resources.ResourceManager.GetObject(imageName);
     return((Drawing.Bitmap)bmp.GetThumbnailImage(Settings.Default.IconSize, Settings.Default.IconSize, ThumbnailCallback, IntPtr.Zero));
 }
コード例 #40
0
ファイル: USPSRepository.cs プロジェクト: prakashgbpecmca/FR8
        public string DownloadExpressUSPSImage(CourierPieceDetail pieceDetails, int totalPiece, int count, int ExpressShipmentid)
        {
            string Imagename = string.Empty;

            if (pieceDetails.ImageUrl != null)
            {
                string labelName = string.Empty;
                labelName = FrayteShortName.USPS;

                // Create a file to write to.
                Imagename = labelName + "_" + pieceDetails.PieceTrackingNumber + "_" + DateTime.Now.ToString("dd_MM_yyyy") + " (" + count + " of " + totalPiece + ")" + ".png";
                if (AppSettings.LabelSave == "")
                {
                    if (System.IO.Directory.Exists(AppSettings.WebApiPath + "/PackageLabel/Express/" + ExpressShipmentid + "/"))
                    {
                        File.WriteAllText(AppSettings.WebApiPath + "/PackageLabel/Express/" + ExpressShipmentid + "/" + Imagename, pieceDetails.ImageUrl);
                    }
                    else
                    {
                        System.IO.Directory.CreateDirectory(AppSettings.WebApiPath + "/PackageLabel/Express/" + ExpressShipmentid + "/");
                        File.WriteAllText(AppSettings.WebApiPath + "/PackageLabel/Express/" + ExpressShipmentid + "/" + Imagename, pieceDetails.ImageUrl);
                    }
                }
                else
                {
                    if (System.IO.Directory.Exists(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid + "/"))
                    {
                        if (AppSettings.ShipmentCreatedFrom == "BATCH")
                        {
                            File.WriteAllText(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid + "/" + Imagename, pieceDetails.ImageUrl);
                        }
                        else
                        {
                            string path = HostingEnvironment.MapPath(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid + "/" + Imagename);
                            File.WriteAllText(path, pieceDetails.ImageUrl);
                        }
                    }
                    else
                    {
                        if (AppSettings.ShipmentCreatedFrom == "BATCH")
                        {
                            System.IO.Directory.CreateDirectory(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid);
                            File.WriteAllText(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid + "/" + Imagename, pieceDetails.ImageUrl);
                        }
                        else
                        {
                            System.IO.Directory.CreateDirectory(HostingEnvironment.MapPath(AppSettings.LabelFolder + "/Express/" + ExpressShipmentid));
                            string path = HttpContext.Current.Server.MapPath("~/PackageLabel/Express/" + ExpressShipmentid + "/" + Imagename);
                            try
                            {
                                bool   status = false;
                                byte[] bytes  = Convert.FromBase64String(pieceDetails.ImageUrl);
                                Image  image;
                                using (MemoryStream ms = new MemoryStream(bytes))
                                {
                                    image = Image.FromStream(ms);
                                    System.Drawing.Bitmap bmpUploadedImage = new System.Drawing.Bitmap(image);
                                    System.Drawing.Image  thumbnailImage   = bmpUploadedImage.GetThumbnailImage(812, 1624, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                                    thumbnailImage.Save(@"" + path);
                                }
                                status = File.Exists(path);
                                if (status)
                                {
                                    return(Imagename);
                                }
                                else
                                {
                                    Imagename = string.Empty;
                                }
                            }
                            catch (Exception ex)
                            {
                                Imagename = string.Empty;
                            }
                        }
                    }
                }
            }
            return(Imagename);
        }
コード例 #41
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            UserProfileInfo objinfo     = new UserProfileInfo();
            string          filename    = "";
            string          thumbTarget = Server.MapPath("~/Modules/Admin/UserManagement/UserPic");
            if (!Directory.Exists(thumbTarget))
            {
                Directory.CreateDirectory(thumbTarget);
            }
            System.Drawing.Image.GetThumbnailImageAbort thumbnailImageAbortDelegate = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            if (fuImage.HasFile)
            {
                string   fName = fuImage.PostedFile.FileName;
                FileInfo fi    = new FileInfo(fName);
                fName = Path.GetFileName(fName);
                string ext = fi.Extension.ToLower();
                if (ext == ".jpeg" || ext == ".jpg" || ext == ".png")
                {
                    double fs = fuImage.PostedFile.ContentLength / (1024 * 1024);
                    if (fs > 3)
                    {
                        ShowHideProfile();
                        ShowMessage("", GetSageMessage("UserManagement", "ImageTooLarge"), "", SageMessageType.Alert);
                        return;
                    }
                    else
                    {
                        Random ran  = new Random();
                        int    rand = ran.Next(1111111, 9999999);
                        if (!File.Exists(Server.MapPath("~/Modules/Admin/UserManagement/UserPic/" + fName)))
                        {
                            string fullfileName = Path.GetFileNameWithoutExtension(fName) + rand + ext;
                            Session[SessionKeys.Profile_Image] = fullfileName;
                            imgUser.ImageUrl = "~/Modules/Admin/UserManagement/UserPic/" + fullfileName;
                            using (
                                System.Drawing.Bitmap originalImage =
                                    new System.Drawing.Bitmap(fuImage.PostedFile.InputStream))
                            {
                                using (
                                    System.Drawing.Image thumbnail = originalImage.GetThumbnailImage(200, 150,
                                                                                                     thumbnailImageAbortDelegate,
                                                                                                     IntPtr.Zero))
                                {
                                    thumbnail.Save(System.IO.Path.Combine(thumbTarget, fullfileName));
                                }
                            }
                        }
                    }
                }
                else
                {
                    {
                        ShowHideProfile();
                        ShowMessage("", GetSageMessage("UserManagement", "InvalidImageFormat"), "", SageMessageType.Error);
                        return;
                    }
                }
            }

            if (filename == "")
            {
                if (Session[SessionKeys.Profile_Image] != null)
                {
                    filename = Session[SessionKeys.Profile_Image].ToString();
                }
                btnDeleteProfilePic.Visible = false;
            }
            else
            {
                btnDeleteProfilePic.Visible = true;
            }
            objinfo.Image       = filename;
            objinfo.UserName    = GetUsername;
            objinfo.FirstName   = txtFName.Text;
            objinfo.LastName    = txtLName.Text;
            objinfo.FullName    = txtFullName.Text;
            objinfo.Location    = txtLocation.Text;
            objinfo.AboutYou    = txtAboutYou.Text;
            objinfo.Email       = txtEmail1.Text + (txtEmail2.Text != "" ? "," + txtEmail2.Text : "") + (txtEmail3.Text != "" ? ',' + txtEmail3.Text : "");
            objinfo.ResPhone    = txtResPhone.Text;
            objinfo.MobilePhone = txtMobile.Text;
            objinfo.Others      = txtOthers.Text;
            objinfo.AddedOn     = DateTime.Now;
            objinfo.AddedBy     = GetUsername;
            objinfo.UpdatedOn   = DateTime.Now;
            objinfo.PortalID    = GetPortalID;
            objinfo.UpdatedBy   = GetUsername;
            objinfo.BirthDate   = txtBirthDate.Text == string.Empty ? DateTime.Parse(falseDate) : DateTime.Parse(txtBirthDate.Text);
            objinfo.Gender      = rdbGender.SelectedIndex;
            UserProfileController.AddUpdateProfile(objinfo);
            LoadUserDetails();
            divUserInfo.Visible                = true;
            tblEditProfile.Visible             = false;
            tblViewProfile.Visible             = true;
            imgProfileEdit.Visible             = false;
            imgProfileView.Visible             = true;
            btnDeleteProfilePic.Visible        = false;
            divEditprofile.Visible             = true;
            sfUserProfile.Visible              = false;
            Session[SessionKeys.Profile_Image] = null;
            ShowMessage("", GetSageMessage("UserManagement", "UserProfileSavedSuccessfully"), "", SageMessageType.Success);
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
コード例 #42
0
    private void AddUpdateRecord()
    {
        string imagefile          = string.Empty;
        TestimonialController clt = new TestimonialController();
        TestimonialInfo       obj = new TestimonialInfo();

        if (Session["TestimonialID"] != null && Session["TestimonialID"].ToString() != string.Empty)
        {
            obj.TestimonialID = Int32.Parse(Session["TestimonialID"].ToString());
        }
        else
        {
            obj.TestimonialID = 0;
        }

        obj.PortalID        = GetPortalID;
        obj.UserModuleID    = int.Parse(SageUserModuleID);
        obj.UserName        = txtName.Text;
        obj.Address         = txtAddress.Text;
        obj.WebUrl          = txtWeburl.Text;
        obj.Title           = txtTitle.Text;
        obj.Testimonial     = txtTestimonial.Value;
        obj.AddedBy         = GetUsername;
        obj.TestimonialDate = DateTime.Parse(txtDate.Text);
        string TargetFolder = Server.MapPath(basePath + "image/UploadedImages");

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

        imagefile = ProfileImage.FileName.Replace(" ", "_");

        if (Session["Image"] == null && imagefile == "")
        {
            obj.Image = "";
        }
        else if (imagefile == "" && Session["Image"] != null)
        {
            obj.Image = Session["Image"].ToString();
        }
        else
        {
            if (ProfileImage.HasFile)
            {
                System.Drawing.Image.GetThumbnailImageAbort thumbnailImageAbortDelegate = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                obj.Image = imagefile;
                using (System.Drawing.Bitmap originalImage = new System.Drawing.Bitmap(ProfileImage.PostedFile.InputStream))
                {
                    using (System.Drawing.Image thumbnail = originalImage.GetThumbnailImage(250, 150, thumbnailImageAbortDelegate, IntPtr.Zero))
                    {
                        thumbnail.Save(System.IO.Path.Combine(TargetFolder, imagefile));
                    }
                }
            }
        }
        clt.SaveRecord(obj);
        ShowMessage(SageMessageTitle.Information.ToString(), SageMessage.GetSageModuleLocalMessageByVertualPath("Modules/Testimonial/ModuleLocalText", "SaveRecordSuccessfully"), "", SageMessageType.Success);
        LoadRecordsOnGrid();
        divGrid.Visible = true;
        ClearField();
    }
コード例 #43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int               order;
            int               subsectionUID;
            string            projNum;
            DaikonReportImage upFile;
            bool              fileLimit        = true;
            int               fileSizeActual   = 0;
            string            fileLimitMessage = "";

            if (IsPostBack)
            {
                String  currUser   = ((DaikonUser)(Session["currUser"])).Username;
                int     sessionKey = Convert.ToInt32((int)Session["sessionkey"]);
                Boolean fileOK     = false;
                String  mimeType   = "";
                Boolean isScalable = false;
                System.Drawing.Image scaledImage;
                String path          = "";//(@"\\if-srvv-media.ad.ufl.edu\websites$\ifasgallery.ifas.ufl.edu\sare\"); //Server.MapPath("~/assocfiles/");
                String fileExtension = "";

                if (Request.Params["suid"] != null)
                {
                    subsectionUID = Convert.ToInt32(Request.Params["suid"]);
                }
                else
                {
                    subsectionUID = 0;
                }
                order = Convert.ToInt32(Request.Params["order"]);

                if (Request.Params["projNum"] != null)
                {
                    projNum = Request.Params["projNum"];
                }
                else
                {
                    projNum = "";
                }

                if (UploadAssocFile.HasFile)
                {
                    fileExtension = System.IO.Path.GetExtension(UploadAssocFile.FileName).ToLower();
                    //[DaikonFilesGetTypeForExtension]
                    string        fileSQL;
                    string        fileConnString = ConfigurationManager.ConnectionStrings["sareDaikonConnectionString"].ToString();
                    SqlConnection fileConnection;
                    SqlCommand    fileCommand;
                    SqlDataReader fileDataReader;
                    // Get the size in bytes of the file to upload.
                    int fileSize = UploadAssocFile.PostedFile.ContentLength;

                    fileConnection = new SqlConnection(fileConnString);

                    fileSQL                 = "DaikonFilesGetTypeForExtension";
                    fileCommand             = new SqlCommand(fileSQL, fileConnection);
                    fileCommand.CommandType = CommandType.StoredProcedure;
                    fileCommand.Parameters.Add("@extension", SqlDbType.VarChar, 6);

                    fileCommand.Parameters["@extension"].Value = fileExtension;

                    if (fileExtension == ".wma")
                    {
                        path = (@"\\if-srv-video.ad.ufl.edu\video\sare\");
                    }
                    else if (fileExtension == ".asf" || fileExtension == ".asx" || fileExtension == ".avi" || fileExtension == ".mov" ||
                             fileExtension == ".mp4" || fileExtension == ".mpeg" || fileExtension == "mpg" || fileExtension == ".qt")
                    {
                        path = (@"\\if-srvv-media.ad.ufl.edu\websites$\ifasgallery.ifas.ufl.edu\sare\");
                        //string loc = (@"\\if-srv-video.ad.ufl.edu\video\sare\ /USER:If-svc-sare-media zZyYXyTkAO");
                        //System.Diagnostics.Process.Start("net.exe", "use G: " + loc);
                        if (fileSize > 146800640)
                        {
                            fileLimit        = false;
                            fileSizeActual   = fileSize / 1048576;
                            fileLimitMessage = "Maximum File Size limit 140 MB. But you are uploading " + fileSizeActual.ToString() + " MB";
                        }
                    }
                    else
                    {
                        if (fileSize > 31457280)
                        {
                            fileLimit        = false;
                            fileSizeActual   = fileSize / 1048576;
                            fileLimitMessage = "Maximum File Size limit 30 MB. But you are uploading " + fileSizeActual.ToString() + " MB";
                        }
                        else
                        {
                            path = Server.MapPath("~/assocfiles/");
                        }
                    }

                    fileConnection.Open();
                    fileDataReader = fileCommand.ExecuteReader();

                    if (fileDataReader.HasRows && fileLimit)
                    {
                        fileDataReader.Read();
                        fileOK     = (bool)(fileDataReader["allowed"]);
                        mimeType   = fileDataReader["mimetype"].ToString();
                        isScalable = (bool)(fileDataReader["is_scalable"]);
                    }
                    else
                    {
                        fileOK = false;
                    }
                    fileDataReader.Dispose();
                    fileConnection.Dispose();
                }

/*
 *                  String[] allowedExtensions =
 *              { ".gif", ".png", ".jpeg", ".jpg", ".pdf", ".doc", ".ppt", ".mp3", ".mpg", ".mp4", ".xls" };
 *                  for (int i = 0; i < allowedExtensions.Length; i++)
 *                  {
 *                      if (fileExtension == allowedExtensions[i])
 *                      {
 *                          fileOK = true;
 *                          switch (fileExtension)
 *                          {
 *                              case ".pdf":
 *                                  mimeType = "application/pdf";
 *                                  isScalable = false;
 *                                  break;
 *                              case ".gif":
 *                                  mimeType = "image/gif";
 *                                  isScalable = true;
 *                                  break;
 *                              case ".jpg":
 *                                  mimeType = "image/jpeg";
 *                                  isScalable = true;
 *                                  break;
 *                              case ".jpeg":
 *                                  mimeType = "image/jpeg";
 *                                  isScalable = true;
 *                                  break;
 *                              case ".png":
 *                                  mimeType = "image/png";
 *                                  isScalable = true;
 *                                  break;
 *                              case ".doc":
 *                                  mimeType = "application/msword";
 *                                  break;
 *                              case ".xls":
 *                                  mimeType = "application/vnd.ms-excel";
 *                                  break;
 *                              case ".ppt":
 *                                  mimeType = "application/vnd.ms-powerpoint";
 *                                  break;
 *                              case ".mpg":
 *                                  mimeType = "video/mpeg";
 *                                  break;
 *                              case ".mp4":
 *                                  mimeType = "video/mp4";
 *                                  break;
 *                              case ".mp3":
 *                                  mimeType = "audio/mpeg";
 *                                  break;
 *                              default:
 *                                  mimeType = "";
 *                                  break;
 *                          }
 *                      }
 *                  }
 *              }
 */

                if (fileOK)
                {
//                    try
//                    {
                    upFile = new DaikonReportImage();

                    if (subsectionUID > 0)
                    {
                        if (fileExtension == ".asf" || fileExtension == ".asx" || fileExtension == ".avi" || fileExtension == ".mov" ||
                            fileExtension == ".mp4" || fileExtension == ".mpeg" || fileExtension == "mpg" || fileExtension == ".qt")
                        {
                            if (ImpersonateUser("If-svc-sare-media", "", "zZyYXyTkAO"))
                            {
                                UploadAssocFile.PostedFile.SaveAs(path
                                                                  + subsectionUID.ToString()
                                                                  + CleanupFileName(UploadAssocFile.FileName));
                            }
                        }
                        else
                        {
                            UploadAssocFile.PostedFile.SaveAs(path
                                                              + subsectionUID.ToString()
                                                              + CleanupFileName(UploadAssocFile.FileName));
                        }

                        if (isScalable)
                        {
                            scaledImage = new System.Drawing.Bitmap(UploadAssocFile.PostedFile.InputStream);
                            scaledImage.GetThumbnailImage(40, 40, null, System.IntPtr.Zero).Save(path + "tn_" + subsectionUID.ToString() + CleanupFileName(UploadAssocFile.FileName));
                        }

                        upFile.Name         = subsectionUID.ToString() + CleanupFileName(UploadAssocFile.FileName);
                        upFile.NameOriginal = CleanupFileName(UploadAssocFile.FileName);
                        upFile.Order        = order;
                        upFile.Category     = Convert.ToInt32(DropDownList1.SelectedValue);
                        upFile.Caption      = TextBox1.Text;
                        upFile.Mimetype     = mimeType;

                        //impersonationContext.Dispose();
                        //Re-Casting failed repeatedly--not sure why
                        // DaikonReportImage upFile2 = (DaikonReportImage)(upFile);
                        //This order 999 to differentiate between Report and Resource upload
                        if (order == 999)
                        {
                            upFile.saveNewInfoProductImageToDB(currUser, sessionKey, subsectionUID);
                        }
                        else if (order == 777)
                        {
                            upFile.savePDPAttachmentToDB(currUser, sessionKey, projNum);
                        }
                        else
                        {
                            upFile.saveNewReportImageToDB(currUser, sessionKey, subsectionUID);
                        }

                        Label3.Text = "File Data Saved. Close this window to continue.";
                        Session["statusMessage2"] = "File Data Saved.";
                        success.Value             = "true";
                        fileExists.Value          = "true";

                        if (fileExtension == ".asf" || fileExtension == ".asx" || fileExtension == ".avi" || fileExtension == ".mov" ||
                            fileExtension == ".mp4" || fileExtension == ".mpeg" || fileExtension == "mpg" || fileExtension == ".qt")
                        {
                            UndoImpersonation();
                        }
                    }
                    else if (subsectionUID == 0)
                    {
                        Label3.Text = "Data Not Saved. Please enter text into the subsection this file is to be attached to and save the report before uploading files.";
                    }
                    else
                    {
                        UploadAssocFile.PostedFile.SaveAs(path
                                                          + CleanupFileName(UploadAssocFile.FileName));

                        Label3.Text = "Data Not Saved. Files not related to reports are not yet supported, but will still be stored.";
                    }
                    Label1.Text = "File uploaded!";

                    //System.Diagnostics.Process.Start("net.exe", "use /delete G:");

                    Session["statusMessage2"] = "File Uploaded.";
                    Session["fileID"]         = upFile.FileID.ToString();
                    success.Value             = "true";

/*
 *                  }
 *                  catch (Exception ex)
 *                  {
 *                      Label1.Text = "File could not be uploaded.";
 *                  }
 */
                }
                else if (Request.Params["fileid"] != null)
                {
                    if (Request.Form["changeDetails"] != null)
                    {
                        upFile          = new DaikonReportImage(Convert.ToInt32(Request.Params["fileid"]), Convert.ToInt32(Request.Params["order"]));
                        upFile.Category = Convert.ToInt32(DropDownList1.SelectedValue);
                        upFile.Caption  = TextBox1.Text;
                        upFile.saveReportImageToDB(currUser, sessionKey, subsectionUID);
                        Label3.Text = "File data updated! Close this window to continue.";
                        Session["statusMessage2"] = "File Data Saved.";
                        success.Value             = "true";
                    }
                    else if (Request.Form["deleteFile"] != null)
                    {
                        if (Request.Form["confirm"] != null || Request.Form["confirm1"] != null)
                        {
                            upFile = new DaikonReportImage(Convert.ToInt32(Request.Params["fileid"]), Convert.ToInt32(Request.Params["order"]));
                            //This order 999 to differentiate between Report and Resource upload
                            if (order == 999)
                            {
                                upFile.deleteInfoProductImageFromDB(currUser, sessionKey, subsectionUID, Convert.ToInt32(Request.Params["fileid"]));
                            }
                            else if (order == 777)
                            {
                                upFile.deletePDPAttachmentFromDB(currUser, sessionKey, projNum, Convert.ToInt32(Request.Params["fileid"]));
                            }
                            else
                            {
                                upFile.deleteReportImageFromDB(currUser, sessionKey);
                            }
                            //                        form1.Controls.Clear();
                            Label1.Text = "File Deleted! Close this window to continue.";
                            Session["statusMessage2"] = "File Deleted.";
                            success.Value             = "true";

                            /*
                             * string completePath = (@"\\if-srvv-media.ad.ufl.edu\websites$\ifasgallery.ifas.ufl.edu\sare\");
                             * completePath += upFile.Name;
                             * if (System.IO.File.Exists(completePath))
                             * {
                             *
                             *  System.IO.File.Delete(completePath);
                             *
                             * }
                             */
                        }
                        else
                        {
                            Label3.Text = "File can be deleted only with confirm checked.";
                            Session["statusMessage2"] = "File is not deleted.";
                        }
                    }
                }
                else
                {
                    string fileTypesAllow = fileTypeLabel.Text.ToString();

                    if (fileExtension.Length > 0 && fileTypesAllow.IndexOf(fileExtension) == -1)
                    {
                        Label1.Text = "Cannot accept files of this type.";
                    }
                    else
                    {
                        if (fileLimit)
                        {
                            Label1.Text = "";
                        }
                        else
                        {
                            Label1.Text      = fileLimitMessage;
                            Label1.ForeColor = Color.Red;
                            Label1.Visible   = true;
                        }
                    }
                }
            }
            else
            {
                if (Request.Params["suid"] != null)
                {
                    subsectionUID = Convert.ToInt32(Request.Params["suid"]);
                }
                else
                {
                    subsectionUID = 0;
                }

                order = Convert.ToInt32(Request.Params["order"]);

                if (Request.Params["move"] != null)
                {
                    upFile = new DaikonReportImage(Convert.ToInt32(Request.Params["fileid"]));
                    upFile.reorderReportImageInDB(((DaikonUser)(Session["currUser"])).Username, Convert.ToInt32((int)Session["sessionkey"]), subsectionUID, Convert.ToInt32(Request.Params["order"]));
                    Label3.Text = "File data updated! Close this window to continue.";
                    Session["statusMessage2"] = "File Data Saved.";
                    success.Value             = "true";
                    return;
                }
                if (Request.Params["fileid"] != null)
                {
                    upFile        = new DaikonReportImage(Convert.ToInt32(Request.Params["fileid"]), order);
                    TextBox1.Text = upFile.Caption;
                    DropDownList1.SelectedValue = upFile.Category.ToString();
                    if (upFile.Category < 3)
                    {
                        Image1.ImageUrl = "./assocfiles/" + upFile.Name;

                        //Image1.ImageUrl = "http://ifasgallery.ifas.ufl.edu/sare/" + upFile.Name;
                    }

                    Label1.Text             = "Update Details for: " + upFile.NameOriginal;
                    UploadAssocFile.Enabled = false;
                    fileExists.Value        = "true";
                }
                else
                {
                    DropDownList1.SelectedValue = DefaultDropDownSelect();
                }


                if (Request.Params["order"] != null && Request.Params["order"] == "999")
                {
                    productInfo.Value = "true";
                    if (Request.Params["title"] != null)
                    {
                        TextBox1.Text = Request.Params["title"].ToString();
                    }
                }
                else
                {
                    Label2.Text = "Order: " + order.ToString();
                }
            }
        }
コード例 #44
0
 protected override void DoInitialize()
 {
     {
         var computeProgram = new ShaderProgram();
         var shaderCode     = new ShaderCode(File.ReadAllText(
                                                 @"06ImageProcessing\ImageProcessing.comp"), ShaderType.ComputeShader);
         var shader = shaderCode.CreateShader();
         computeProgram.Create(shader);
         shader.Delete();
         this.computeProgram = computeProgram;
     }
     {
         Bitmap bitmap = new System.Drawing.Bitmap(this.textureFilename);
         if (bitmap.Width != 512 || bitmap.Height != 512)
         {
             bitmap = (Bitmap)bitmap.GetThumbnailImage(512, 512, null, IntPtr.Zero);
         }
         OpenGL.GenTextures(1, this.input_image);
         OpenGL.BindTexture(OpenGL.GL_TEXTURE_2D, this.input_image[0]);
         //  Lock the image bits (so that we can pass them to OGL).
         BitmapData bitmapData = bitmap.LockBits(
             new Rectangle(0, 0, bitmap.Width, bitmap.Height),
             ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
         //GL.ActiveTexture(GL.GL_TEXTURE0);
         OpenGL.TexImage2D(OpenGL.GL_TEXTURE_2D, 0, (int)OpenGL.GL_RGBA32F,
                           bitmap.Width, bitmap.Height, 0, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE,
                           bitmapData.Scan0);
         //  Unlock the image.
         bitmap.UnlockBits(bitmapData);
         /* We require 1 byte alignment when uploading texture data */
         //GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
         /* Clamping to edges is important to prevent artifacts when scaling */
         OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, (int)OpenGL.GL_CLAMP_TO_EDGE);
         OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, (int)OpenGL.GL_CLAMP_TO_EDGE);
         /* Linear filtering usually looks best for text */
         OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, (int)OpenGL.GL_LINEAR);
         OpenGL.TexParameteri(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, (int)OpenGL.GL_LINEAR);
         bitmap.Dispose();
     }
     {
         //GL.ActiveTexture(GL.GL_TEXTURE0);
         OpenGL.GenTextures(1, this.intermediate_image);
         OpenGL.BindTexture(OpenGL.GL_TEXTURE_2D, this.intermediate_image[0]);
         OpenGL.TexStorage2D(TexStorage2DTarget.Texture2D, 8, OpenGL.GL_RGBA32F, 512, 512);
     }
     {
         // This is the texture that the compute program will write into
         //GL.ActiveTexture(GL.GL_TEXTURE0);
         OpenGL.GenTextures(1, this.output_image);
         OpenGL.BindTexture(OpenGL.GL_TEXTURE_2D, this.output_image[0]);
         OpenGL.TexStorage2D(TexStorage2DTarget.Texture2D, 8, OpenGL.GL_RGBA32F, 512, 512);
     }
     {
         var          bufferable   = new ImageProcessingModel();
         ShaderCode[] simpleShader = new ShaderCode[2];
         simpleShader[0] = new ShaderCode(File.ReadAllText(@"06ImageProcessing\ImageProcessing.vert"), ShaderType.VertexShader);
         simpleShader[1] = new ShaderCode(File.ReadAllText(@"06ImageProcessing\ImageProcessing.frag"), ShaderType.FragmentShader);
         var propertyNameMap = new PropertyNameMap();
         propertyNameMap.Add("vert", "position");
         propertyNameMap.Add("uv", "uv");
         var pickableRenderer = new PickableRenderer(
             bufferable, simpleShader, propertyNameMap, "position");
         pickableRenderer.Name = string.Format("Pickable: [ImageProcessingRenderer]");
         pickableRenderer.Initialize();
         pickableRenderer.SetUniform("output_image",
                                     new samplerValue(
                                         BindTextureTarget.Texture2D, this.output_image[0], OpenGL.GL_TEXTURE0));
         this.renderer = pickableRenderer;
     }
 }