Example #1
0
    private void ScaleImages(string screenshotFolderPath, IList <ImageData> imageDataList)
    {
        string thumbnailsFolderPath = Path.Combine(screenshotFolderPath, ThumbnailsFolderName);
        string previewsFolderPath   = Path.Combine(screenshotFolderPath, PreviewsFolderName);

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

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

        foreach (ImageData image in imageDataList)
        {
            string imagePath     = Path.Combine(screenshotFolderPath, image.FileName);
            string thumbnailPath = Path.Combine(thumbnailsFolderPath, GetThumnailName(image.FileName));
            string previewPath   = Path.Combine(previewsFolderPath, GetPreviewImageName(image.FileName));

            if (!File.Exists(thumbnailPath) || !File.Exists(previewPath))
            {
                using (BaseImage originalImage = BaseImage.FromFile(imagePath),
                       thumbnail = ImageThumnails.GenerateThumbnail(originalImage, new Size(100, 100)),
                       preview = ImageThumnails.GenerateThumbnail(originalImage, new Size(640, 480)))
                {
                    thumbnail.Save(thumbnailPath);
                    preview.Save(previewPath);
                }
            }
        }
    }
Example #2
0
        private void photoButton_Click(object sender, EventArgs e)
        {
            var f = new OpenFileDialog
            {
                Filter           = "JPG (*.JPG)|*.jpg",
                InitialDirectory = (photoButton.Text == "Portrait photo")
                    ? Path.Combine(Path.GetDirectoryName(Directory.GetCurrentDirectory()), "portrait photos")
                    : Path.Combine(Path.GetDirectoryName(Directory.GetCurrentDirectory()), "art photos")
            };

            if (f.ShowDialog() == DialogResult.OK)
            {
                _imageFileName   = f.FileName;
                pictureBox.Image = Image.FromFile(_imageFileName);
                switch (photoButton.Text)
                {
                case "Portrait photo":
                    photoButton.Text = "Fine-art photo";
                    EnableRemovePhotoButton();
                    break;

                case "Fine-art photo":
                    photoButton.Text = "Portrait photo";
                    EnableRemovePhotoButton();
                    break;
                }
            }
        }
Example #3
0
        public static List <Bitmap> GetFrames(string fileName)
        {
            var tmpFrames = new List <byte[]>();

            // Check the image format to determine what format
            // the image will be saved to the memory stream in
            var guidToImageFormatMap = new Dictionary <Guid, ImageFormat>()
            {
                { ImageFormat.Bmp.Guid, ImageFormat.Bmp },
                { ImageFormat.Gif.Guid, ImageFormat.Png },
                { ImageFormat.Icon.Guid, ImageFormat.Png },
                { ImageFormat.Jpeg.Guid, ImageFormat.Jpeg },
                { ImageFormat.Png.Guid, ImageFormat.Png }
            };

            using (var gifImg = Image.FromFile(fileName, true))
            {
                var imageGuid = gifImg.RawFormat.Guid;

                var imageFormat = (from pair in guidToImageFormatMap where imageGuid == pair.Key select pair.Value).FirstOrDefault();

                if (imageFormat == null)
                {
                    throw new NoNullAllowedException("Unable to determine image format");
                }

                //Get the frame count
                var dimension  = new FrameDimension(gifImg.FrameDimensionsList[0]);
                var frameCount = gifImg.GetFrameCount(dimension);

                //Step through each frame
                for (var i = 0; i < frameCount; i++)
                {
                    //Set the active frame of the image and then
                    gifImg.SelectActiveFrame(dimension, i);

                    //write the bytes to the tmpFrames array
                    using (var ms = new MemoryStream())
                    {
                        gifImg.Save(ms, imageFormat);
                        tmpFrames.Add(ms.ToArray());
                    }
                }

                //Get list of frame(s) from image file.
                var myBitmaps = new List <Bitmap>();

                foreach (var item in tmpFrames)
                {
                    var tmpBitmap = ConvertBytesToImage(item);

                    if (tmpBitmap != null)
                    {
                        myBitmaps.Add(tmpBitmap);
                    }
                }

                return(myBitmaps);
            }
        }
Example #4
0
        public EventHall(GameContext context) : base(context)
        {
            if (EmptyMap == null)
            {
                EmptyMap = (Bitmap)Image.FromFile(Path.Combine(Path.GetDirectoryName(typeof(EventHall).Assembly.Location), "eventhall.png"));
            }

            if (EventTypeDetectors == null)
            {
                EventTypeDetectors = new List <Tuple <uint[], Type> >();
                using (var reader = File.OpenText(Path.Combine(Path.GetDirectoryName(typeof(EventHall).Assembly.Location), "eventData.txt"))) {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            continue;
                        }
                        var items = line.Split('\t');
                        var t     = Type.GetType("IBDTools.Screens." + items[0], false, true);
                        if (t == null)
                        {
                            continue;
                        }
                        EventTypeDetectors.Add(Tuple.Create(items.Skip(1).Select(x => uint.Parse(x.Substring(2), NumberStyles.HexNumber)).ToArray(), t));
                    }
                }
            }
        }
 internal static void SystemDrawingResize(string path, int size, string outputDirectory)
 {
     using (var image = SystemDrawingImage.FromFile(path, true))
     {
         var scaled  = ScaledSize(image.Width, image.Height, size);
         var resized = new Bitmap(scaled.width, scaled.height);
         using (var graphics = Graphics.FromImage(resized))
             using (var attributes = new ImageAttributes())
             {
                 attributes.SetWrapMode(WrapMode.TileFlipXY);
                 graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                 graphics.CompositingMode    = CompositingMode.SourceCopy;
                 graphics.CompositingQuality = CompositingQuality.AssumeLinear;
                 graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                 graphics.DrawImage(image, Rectangle.FromLTRB(0, 0, resized.Width, resized.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
                 // Save the results
                 using (var output = File.Open(OutputPath(path, outputDirectory, SystemDrawing), FileMode.Create))
                     using (var encoderParams = new EncoderParameters(1))
                         using (var qualityParam = new EncoderParameter(Encoder.Quality, (long)Quality))
                         {
                             encoderParams.Param[0] = qualityParam;
                             resized.Save(output, systemDrawingJpegCodec, encoderParams);
                         }
             }
     }
 }
Example #6
0
        public void DetectShapes()
        {
            int       count                    = 40;
            int       minSize                  = 5;
            int       maxSize                  = 80;
            var       image                    = (Bitmap)Image.FromFile(@"C:\Users\marco\Downloads\PanoBeam\capture_pattern0.png");
            Rectangle clippingRectangle        = new Rectangle(new Point(563, 360), new Size(1156, 382));
            var       clippingRectangleCorners = new[]
            {
                new AForge.IntPoint(clippingRectangle.X, clippingRectangle.Y),
                new AForge.IntPoint(clippingRectangle.X + clippingRectangle.Width, clippingRectangle.Y),
                new AForge.IntPoint(clippingRectangle.X + clippingRectangle.Width, clippingRectangle.Y + clippingRectangle.Height),
                new AForge.IntPoint(clippingRectangle.X, clippingRectangle.Y + clippingRectangle.Height)
            };

            Helpers.FillOutsideBlack(image, clippingRectangleCorners);

            var blobCounter = new AForge.Imaging.BlobCounter();

            AForge.Imaging.Blob[] blobs;
            blobCounter.FilterBlobs = true;
            blobCounter.MaxHeight   = maxSize;
            blobCounter.MaxWidth    = maxSize;
            blobCounter.MinHeight   = minSize;
            blobCounter.MinWidth    = minSize;

            var threshold = Recognition.GetThreshold(image);

            blobCounter.BackgroundThreshold = Color.FromArgb(255, threshold, threshold, threshold);
            blobCounter.ProcessImage(image);
            blobs = blobCounter.GetObjectsInformation();
        }
Example #7
0
        public static void Iniciar()
        {
            Image          image      = Image.FromFile(@"C:\Users\900103\Desktop\terra1.gif");
            FrameDimension dimension  = new FrameDimension(image.FrameDimensionsList[0]);
            int            frameCount = image.GetFrameCount(dimension);
            StringBuilder  sb;

            int left = Console.WindowLeft, top = Console.WindowTop;

            char[] chars = { '.', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ' };

            for (int i = 0; ; i = (i + 1) % frameCount)
            {
                sb = new StringBuilder();
                image.SelectActiveFrame(dimension, i);

                for (int h = 0; h < image.Height; h++)
                {
                    for (int w = 0; w < image.Width; w++)
                    {
                        Color cl    = ((Bitmap)image).GetPixel(w, h);
                        int   gray  = (cl.R + cl.R + cl.B) / 3;
                        int   index = (gray * (chars.Length - 1)) / 255;

                        sb.Append(chars[index]);
                    }
                    sb.Append('\n');
                }

                Console.SetCursorPosition(left, top);
                Console.Write(sb.ToString());

                System.Threading.Thread.Sleep(200);
            }
        }
        protected void btncrop_Click(object sender, EventArgs e)
        {
            string path = "";

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                path = "~/uploads/" + Membership.GetUser().ProviderUserKey.ToString() + "/ProfileCover";
            }
            try
            {
                string    fname     = Membership.GetUser().ProviderUserKey.ToString() + ".jpg";
                string    fpath     = Path.Combine(Server.MapPath(path), fname);
                Image     oimg      = Image.FromFile(fpath);
                Rectangle cropcords = new Rectangle(
                    Convert.ToInt32(hdnx.Value),
                    Convert.ToInt32(hdny.Value),
                    Convert.ToInt32(hdnw.Value),
                    Convert.ToInt32(hdnh.Value));
                string   cfname, cfpath;
                Bitmap   bitMap = new Bitmap(cropcords.Width, cropcords.Height, oimg.PixelFormat);
                Graphics grph   = Graphics.FromImage(bitMap);
                grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel);
                cfname = "c" + fname;
                cfpath = Path.Combine(Server.MapPath(path), cfname);
                bitMap.Save(cfpath);
                imgcropped.Visible = true;
                imgcropped.Src     = path + "/" + cfname;
                // imgcrop.Src = path + "/" + cfname;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #9
0
        private Stream GetWatermarkedImageStream()
        {
            Image watermarkedImage = null;

            try
            {
                try
                {
                    watermarkedImage = ImageHelper.AddWatermark(MediaObjectFilePath, MediaObject.GalleryId);
                }
                catch (Exception ex)
                {
                    // Can't apply watermark to image. Substitute an error image and send that to the user.
                    if (!(ex is FileNotFoundException))
                    {
                        // Don't log FileNotFoundException exceptions. This helps avoid clogging the error log
                        // with entries caused by search engine retrieving media objects that have been moved or deleted.
                        AppEventController.LogError(ex);
                    }
                    watermarkedImage = Image.FromFile(_context.Request.MapPath(String.Concat(Utils.SkinPath, "/images/error-xl.png")));
                }

                MemoryStream stream = new MemoryStream();
                watermarkedImage.Save(stream, ImageFormat.Jpeg);
                return(stream);
            }
            finally
            {
                if (watermarkedImage != null)
                {
                    watermarkedImage.Dispose();
                }
            }
        }
Example #10
0
        public override void Solve()
        {
            var pparser = new Pparser(FpatIn);

            int cletter, ccol, crow;

            pparser.Fetch(out cletter, out ccol, out crow);

            var rgletter = new Letter[cletter];

            for (int i = 0; i < cletter; i++)
            {
                rgletter[i] =
                    new Letter(pparser.Fetch <string>(), pparser.FetchN <string>(crow).ToArray());
            }

            var bmpSrc = (Bitmap)Image.FromFile(FpatIn.Replace(".in", ".png"));
            var mp     = ReadLetters(bmpSrc, rgletter);

            using (Output)
                foreach (var letter in rgletter)
                {
                    Solwrt.WriteLine(letter.Ch + " " + mp[letter]);
                }
        }
Example #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            PrivateFontCollection collection = new PrivateFontCollection();

            // Add the custom font families.
            // (Alternatively use AddMemoryFont if you have the font in memory, retrieved from a database).
            collection.AddFontFile(Server.MapPath("Content/privatefont.ttf"));
            string secondText = "RAJASTHAN JANARDAN RAI NAGAR VIDYAPEET UNIVERSITY";

            string imageFilePath = Server.MapPath("Content/certificate_mba.jpeg");
            Bitmap bitmap        = (Bitmap)Image.FromFile(imageFilePath);//load the image file

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                Brush b = new SolidBrush(Color.Black);
                using (Font f = new Font(collection.Families.First(), 36))
                {
                    PointF firstLocation = new PointF(405f, 400f);
                    graphics.DrawString("Shri Mahendra Lohar", f, b, firstLocation);
                }
                using (Font f = new Font("Roboto", 18))
                {
                    SizeF  stringSize     = graphics.MeasureString(secondText, f);
                    PointF secondLocation = new PointF((bitmap.Width - stringSize.Width) / 2, 380f);
                    graphics.DrawString(secondText.ToUpper(), f, Brushes.White, secondLocation);
                }
            }
            bitmap.Save(Server.MapPath("certificateimage/certificate_mba.JPG"));
        }
Example #12
0
        /// <summary>
        /// 截图
        /// </summary>
        private void CaptureImage(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            var rect = Screen.PrimaryScreen.Bounds;
            var size = new Size(pbImg.Width, pbImg.Height);

            using (var bitmap = new Bitmap(rect.Width, rect.Height))
            {
                var grp      = Graphics.FromImage(bitmap);
                var location = new Point(Left + 8, Top + 32);

                grp.CopyFromScreen(location, new Point(0, 0), size);
                grp.ReleaseHdc(grp.GetHdc());
                bitmap.Save(filePath);
            }

            using (var srcImg = Image.FromFile(filePath))
                using (var bitmap = new Bitmap(pbImg.Width, pbImg.Height))
                    using (var grp = Graphics.FromImage(bitmap))
                    {
                        grp.DrawImage(srcImg, 0, 0, new Rectangle(new Point(), size), GraphicsUnit.Pixel);
                        srcImg.Dispose();

                        using (Image newImg = Image.FromHbitmap(bitmap.GetHbitmap()))
                            newImg.Save(filePath, ImageFormat.Jpeg);
                    }
        }
Example #13
0
        private static void WriteBitmap(Bitmap textureMap, string texPath, int textureSize, ref int countX, ref int countY)
        {
            var file = $"{SharpCraft.Instance.GameFolderDir}/assets/sharpcraft/textures/{texPath}.png";

            Bitmap tex;

            if (File.Exists(file))
            {
                using (var loaded = Image.FromFile(file))
                {
                    tex = new Bitmap(loaded, textureSize, textureSize);
                }
            }
            else
            {
                tex = new Bitmap(TextureManager.TEXTURE_MISSING, textureSize, textureSize);
            }

            using (tex)
            {
                using (Graphics g = Graphics.FromImage(textureMap))
                {
                    g.DrawImage(tex, countX, countY);

                    countX += textureSize;

                    if (countX + textureSize > textureMap.Width)
                    {
                        countX  = 0;
                        countY += textureSize;
                    }
                }
            }
        }
Example #14
0
        /// <summary>
        /// Делает скриншот из указанного файла
        /// </summary>
        /// <param name="filename">Путь к видеофайлу</param>
        /// <param name="position">Время скриншота</param>
        /// <param name="resolution">Разрешение скринщота</param>
        /// <returns>Изображение со скриншотом</returns>
        public Image TakeScreenshot(string filename, TimeSpan position, Size resolution)
        {
            var output = Path.GetTempFileName();

            string arguments = String.Format("-ss {1}:{2}:{3}.{4} -i \"{0}\" -vframes 1 -f image2 -s {5}x{6} \"{7}\"",
                                             filename,
                                             position.Hours,
                                             position.Minutes,
                                             position.Seconds,
                                             position.Milliseconds,
                                             resolution.Width,
                                             resolution.Height,
                                             output
                                             );

            Execute(arguments, true);

            var img = Image.FromFile(output);

            try
            {
                if (File.Exists(output))
                {
                    File.Delete(output);
                }
            }
            catch
            {
            }

            return(img);
        }
Example #15
0
 /// <summary>
 /// Gets size of image located in medals directory.
 /// </summary>
 /// <param name="filename">
 /// Name of file.
 /// </param>
 /// <returns>
 /// Size of image.
 /// </returns>
 private Size GetImageSize(string filename)
 {
     using (Image img = Image.FromFile(Server.MapPath("{0}{1}/{2}".FormatWith(YafForumInfo.ForumServerFileRoot, YafBoardFolders.Current.Medals, filename))))
     {
         return(img.Size);
     }
 }
        private void LoadExistsImages()
        {
            _existsImages.Clear();

            DirectoryInfo destDirInfo = this.GetDestDirectory();

            FileInfo[] fileInfos = destDirInfo.GetFiles();

            foreach (var fileInfo in fileInfos)
            {
                try
                {
                    var fileName = Path.Combine(EnvVariables.DestPath, fileInfo.Name);
                    var image    = Image.FromFile(fileName);

                    using (var memoryStream = new MemoryStream())
                    {
                        image.Save(memoryStream, image.RawFormat);
                        _existsImages.Add(Convert.ToBase64String(memoryStream.ToArray()));
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Example #17
0
        private void ProcessMediaObjectWithWatermark()
        {
            // Send the specified file to the client with the watermark overlayed on top.
            IMimeType mimeType = MimeType.LoadInstanceByFilePath(this._filename);

            this._context.Response.Clear();
            this._context.Response.ContentType = mimeType.FullType;

            Image watermarkedImage = null;

            try
            {
                try
                {
                    watermarkedImage = ImageHelper.AddWatermark(this._filepath);
                }
                catch (Exception ex)
                {
                    // Can't apply watermark to image. Substitute an error image and send that to the user.
                    AppErrorController.LogError(ex);
                    watermarkedImage = Image.FromFile(this._context.Request.MapPath(String.Concat(Util.GalleryRoot, "/images/error_48x48.png")));
                }

                watermarkedImage.Save(this._context.Response.OutputStream, ImageFormat.Jpeg);
            }
            finally
            {
                if (watermarkedImage != null)
                {
                    watermarkedImage.Dispose();
                }
            }
        }
Example #18
0
        //给指定文件夹下面的图片加水印
        private void Watermarkbtn_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1 = new FolderBrowserDialog();
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                SavePath = folderBrowserDialog1.SelectedPath;
            }
            InitWaterMark();
            //设置水印字体
            Font font = SetFont();
            //设置水印字体的填充颜色,填充透明度
            SolidBrush solidBrush = SetColorAndTransparnece();

            for (int i = 0; i < Count; i++)
            {
                //Mtext.Text = "正在处理文件:" + ImageName[i];
                CurPath = ImagePaths[i];
                using (Image image = Image.FromFile(CurPath))
                {
                    Bitmap   bitmap;
                    Graphics graphics;
                    GenerateWaterMarking(font, solidBrush, image, out bitmap, out graphics);
                    bitmap.Save(SavePath + "//" + ImageName[i], System.Drawing.Imaging.ImageFormat.Jpeg);
                    graphics.Dispose();
                    bitmap.Dispose();
                    image.Dispose();
                }
            }
            Mtext.Text = "一键加水印成功";
        }
Example #19
0
        private static void Main(string[] args)

        {
            var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var doc = new Document(PageSize.A4, 0, 0, 0, 0);

            var pdfFileStream = new FileStream(Path.Combine(location, $"{Folder}.pdf"), FileMode.Create);

            PdfWriter.GetInstance(doc, pdfFileStream);

            doc.Open();

            foreach (var file in Directory.GetFiles(Path.Combine(location, Folder)).OrderBy(x => x))

            {
                var originalImage = Image.FromFile(file);

                var resizedImage = (Image) new Bitmap(originalImage,
                                                      new Size(originalImage.Width / ResizeRatio, originalImage.Height / ResizeRatio));

                var im = iTextSharp.text.Image.GetInstance(resizedImage, ImageFormat.Jpeg);
                im.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);

                doc.Add(im);

                doc.NewPage();
            }
            doc.Close();
        }
Example #20
0
 internal static void SystemDrawingResize(string path, int size, string outputDirectory)
 {
     using (var image = SystemDrawingImage.FromFile(path, true))
     {
         int width, height;
         if (image.Width > image.Height)
         {
             width  = size;
             height = Convert.ToInt32(image.Height * size / (double)image.Width);
         }
         else
         {
             width  = Convert.ToInt32(image.Width * size / (double)image.Height);
             height = size;
         }
         var resized = new Bitmap(width, height);
         using (var graphics = Graphics.FromImage(resized))
             using (var attributes = new ImageAttributes())
             {
                 attributes.SetWrapMode(WrapMode.TileFlipXY);
                 graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                 graphics.CompositingQuality = CompositingQuality.HighSpeed;
                 graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                 graphics.CompositingMode    = CompositingMode.SourceCopy;
                 graphics.DrawImage(image, Rectangle.FromLTRB(0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
                 // Save the results
                 using (var output = File.Open(OutputPath(path, outputDirectory, SystemDrawing), FileMode.Create))
                 {
                     resized.Save(output, _codec, _encoderParameters);
                 }
             }
     }
 }
Example #21
0
        private void ResizeWithSystemDrawing(string filePath, string resizedFilePath, int size)
        {
            var image = DrawingImage.FromFile(filePath);

            var destRect  = new DrawingRectangle(0, 0, size, size);
            var destImage = new DrawingBitmap(size, size);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = DrawingGraphics.FromImage(destImage))
            {
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            destImage.Save(resizedFilePath);
        }
        private void MenuItemFileOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PNG Image|*.png|TIFF Image|*.tiff|TIFF Image|*.tif";
            if (openFileDialog.ShowDialog() == true)
            {
                Uri fileUri = new Uri(openFileDialog.FileName);
                loadedImage.Source = new BitmapImage(fileUri);
                Image img = Image.FromFile(openFileDialog.FileName);
                bitmapImage = new Bitmap(openFileDialog.FileName);
                MemoryStream MS = new MemoryStream();
                bitmapImage.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmapImage = new Bitmap(MS);


                using (MemoryStream memory = new MemoryStream())
                {
                    bitmapImage.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                    memory.Position = 0;
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = memory;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    modifiedImage.Source = bitmap;
                }
            }
        }
Example #23
0
    void Awake()
    {
        rawImage = GetComponent <RawImage>();
        if (rawImage == null)
        {
            return;
        }

        var gifImage   = Image.FromFile(basePath + pictureName + ".gif");
        var dimension  = new FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);

        for (int i = 0; i < frameCount; i++)
        {
            gifImage.SelectActiveFrame(dimension, i);
            var frame = new Bitmap(gifImage.Width, gifImage.Height);
            System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);
            var frameTexture = new Texture2D(frame.Width, frame.Height);
            for (int x = 0; x < frame.Width; x++)
            {
                for (int y = 0; y < frame.Height; y++)
                {
                    System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                    frameTexture.SetPixel(frame.Width - 1 - x, frame.Height - 1 - y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A));                     // for some reason, x is flipped
                }
            }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
        }
    }
Example #24
0
        //Utilities
        public void ShowGreetings()
        {
            GreetingLabel.Show();
            GreetingLabel.ForeColor = Color.White;
            GreetingLabel.Text      = string.Format(Constants.GreetingsMessage,
                                                    AuthenticationManager.GetCurrentUser().Username);

            //Show Image
            User currentUser = AuthenticationManager.GetCurrentUser();

            byte[] imageBytes = imageService.GetProfilePicture(currentUser.Username);
            if (imageBytes != null)
            {
                System.Drawing.Image image = imageService.byteArrayToImage(imageBytes);
                profilePicPictureBox.Image = imageService.ScaleImage(image, 55, 54);
                profilePicPictureBox.Size  = new Size(profilePicPictureBox.Image.Width,
                                                      profilePicPictureBox.Image.Height);
            }
            else
            {
                Image        image        = Image.FromFile(@"../../Utilities/Images/default.jpg");
                byte[]       imageToBytes = imageService.imageToByteArray(image);
                Models.Image newImage     = new Models.Image()
                {
                    Content = imageToBytes
                };
                currentUser.ProfilePicture = newImage;
                profilePicPictureBox.Image = imageService.ScaleImage(image, 55, 54);
            }
            profilePicPictureBox.Location = new Point(590, profilePicPictureBox.Location.Y);
            profilePicPictureBox.Show();
            LogoutButton.Show();
        }
Example #25
0
 public static string ExtractFromPath(string pathToQrCodeImage)
 {
     using (var bitmap = (Bitmap)Image.FromFile(pathToQrCodeImage))
     {
         return(ExtractFromBitmap(bitmap));
     }
 }
 public ActionResult Upload(HttpPostedFileBase upload, string tooltip, int gallID, string gName)
 {
     if (upload != null)
     {
         string fileName  = Path.GetFileName(upload.FileName);
         string fullVpath = Server.MapPath($"~/Resources/PhotoStorage/{gallID}/" + fileName);
         upload.SaveAs(fullVpath);
         Bitmap mini      = new Bitmap(Image.FromFile(fullVpath), 200, 150);
         string miniVpath = Server.MapPath($"~/Resources/PhotoStorage/{gallID}/" + "mini" + fileName);
         mini.Save(miniVpath);
         GalleryDBEntities gm = new GalleryDBEntities();
         int maxNum           = 0;
         var pictures         = from picture in gm.PICTURE_LIST where picture.Gallery_ID == gallID select picture;
         foreach (var pic in pictures)
         {
             if (maxNum < pic.Picture_Number)
             {
                 maxNum = pic.Picture_Number;
             }
         }
         PICTURE_LIST newPic = new PICTURE_LIST
         {
             Description    = tooltip,
             Full_Version   = fileName,
             Gallery_ID     = gallID,
             Mini_Version   = "mini" + fileName,
             Picture_Number = maxNum + 1
         };
         gm.PICTURE_LIST.Add(newPic);
         gm.SaveChanges();
     }
     return(GalleryDetailsLogedIn(gName));
 }
        /*
         * public static TextureBlockUV GetUVsFromBlock(EnumBlock block)
         * {
         *  _blockUVs.TryGetValue(block, out TextureBlockUV uv);
         *
         *  if (uv == null)
         *      _blockUVs.TryGetValue(EnumBlock.MISSING, out uv);
         *
         *  return uv;
         * }*/

        private static void DrawToBitmap(Bitmap to, int x, int y, string file)
        {
            using (Bitmap bmp = (Bitmap)Image.FromFile(file))
            {
                DrawToBitmap(to, x, y, bmp);
            }
        }
Example #28
0
        public static SysImage ToImageFile(this byte[] array)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }

            var name = Path.GetRandomFileName();

            try
            {
                File.WriteAllBytes(name, array);
                return(SysImage.FromFile(name));
            }
            finally
            {
                try
                {
                    if (File.Exists(name))
                    {
                        File.Delete(name);
                    }
                }
                catch
                {
                    //No errors during delete
                }
            }
        }
Example #29
0
        private void OnExampleLoadClicked(object sender, RoutedEventArgs eargs)
        {
            if (solver == null || renderer == null)
            {
                return;
            }

            try
            {
                int shotid = iudExample.Value.Value;

                if (!File.Exists(String.Format("./example/shot{0:000}.png", shotid)))
                {
                    return;
                }

                Image  file = Image.FromFile(String.Format("./example/shot{0:000}.png", shotid));
                Bitmap bmp  = new Bitmap(file.Width, file.Height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.DrawImageUnscaled(file, 0, 0);
                }

                imgDisplay.Source = LoadBitmap(solver.LoadScreenshot(bmp));

                pnlExecute.IsEnabled = false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Execption while executing", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// Pick image for face detection and load glasses for image
        /// </summary>
        ///
        private void Glasses_Click(object sender, RoutedEventArgs e)
        {
            if (DetectedResultsInText.Equals("Detecting..."))
            {
                return;
            }

            if (!dlg.FileName.Equals(""))
            {    //Create Image type
                Image renderingImage_img = Image.FromFile(dlg.FileName);
                foreach (var face in faces)
                {
                    // add Glasses to face
                    string.Format("GlassesType: {0}", face.FaceAttributes.Glasses.ToString());

                    if (face.FaceAttributes.Glasses.ToString().Equals("NoGlasses"))
                    {
                        // Gan kinh len
                        renderingImage_img = Add_Glasses(renderingImage_img, face);
                    }
                }
                renderingImage_img.Save("F:\\study\\Project\\New pj\\Cognitive-Face-Windows\\Images\\saveFile\\" + saveImage_Count.ToString() + ".jpg");
                BitmapImage DisplayImage = new BitmapImage(new Uri("F:\\study\\Project\\New pj\\Cognitive-Face-Windows\\Images\\saveFile\\" + saveImage_Count.ToString() + ".jpg"));
                ImageGlassesDisplay.Source = DisplayImage;
                saveImage_Count++;
            }
            else
            {
                DetectedResultsInText = "Please upload a photo";
            }
        }
Example #31
0
 public Image ColorizeImage(string Name, Image Image)
 {
     if (!ColorCache.ContainsKey(Name))
     {
         try
         {
             ColorCache[Name] = Image2Pallet(Image.FromFile(@"Core\Pallet\" + Name + ".png"));
         }
         catch { return Image; }
     }
     return ColorizeImage(ColorCache[Name], Image);
 }