コード例 #1
0
        private static string CreateThumbnail(string strImage)
        {
            var blnCreate = true;

            var strThumbnail = strImage.Replace(Path.GetFileName(strImage), "thumbnail_" + Path.GetFileName(strImage));

            //check if image has changed
            if (File.Exists(strThumbnail))
            {
                if (File.GetLastWriteTime(strThumbnail) == File.GetLastWriteTime(strImage))
                {
                    blnCreate = false;
                }
            }
            if (blnCreate)
            {
                const int intSize = 150;                 //size of the thumbnail
                Image     objImage;
                try
                {
                    objImage = Image.FromFile(strImage);

                    //scale the image to prevent distortion
                    int    intHeight;
                    int    intWidth;
                    double dblScale;
                    if (objImage.Height > objImage.Width)
                    {
                        //The height was larger, so scale the width
                        dblScale  = (double)intSize / objImage.Height;
                        intHeight = intSize;
                        intWidth  = Convert.ToInt32(objImage.Width * dblScale);
                    }
                    else
                    {
                        //The width was larger, so scale the height
                        dblScale  = (double)intSize / objImage.Width;
                        intWidth  = intSize;
                        intHeight = Convert.ToInt32(objImage.Height * dblScale);
                    }

                    //create the thumbnail image
                    var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero);

                    //delete the old file ( if it exists )
                    if (File.Exists(strThumbnail))
                    {
                        File.Delete(strThumbnail);
                    }

                    //save the thumbnail image
                    objThumbnail.Save(strThumbnail, objImage.RawFormat);

                    //set the file attributes
                    File.SetAttributes(strThumbnail, FileAttributes.Normal);
                    File.SetLastWriteTime(strThumbnail, File.GetLastWriteTime(strImage));

                    //tidy up
                    objImage.Dispose();
                    objThumbnail.Dispose();
                }
                catch (Exception ex)                 //problem creating thumbnail
                {
                    Logger.Error(ex);
                }
            }

            strThumbnail = Globals.ApplicationPath + "/" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\"));
            strThumbnail = strThumbnail.Replace("\\", "/");

            //return thumbnail filename
            return(strThumbnail);
        }
コード例 #2
0
        internal static string CreateThumbnail(string strImage)
        {
            var imageFileName = Path.GetFileName(strImage);

            if (string.IsNullOrEmpty(imageFileName) || imageFileName.StartsWith("thumbnail_"))
            {
                strImage = Globals.ApplicationPath + "/" + strImage.Substring(strImage.IndexOf("portals\\"));
                strImage = strImage.Replace("\\", "/");
                return(strImage);
            }

            var strThumbnail = strImage.Replace(Path.GetFileName(strImage), "thumbnail_" + imageFileName);

            if (NeedCreateThumbnail(strThumbnail, strImage))
            {
                lock (_threadLocker)
                {
                    if (NeedCreateThumbnail(strThumbnail, strImage))
                    {
                        const int intSize = 150; //size of the thumbnail
                        try
                        {
                            var objImage = Image.FromFile(strImage);

                            //scale the image to prevent distortion
                            int    intHeight;
                            int    intWidth;
                            double dblScale;
                            if (objImage.Height > objImage.Width)
                            {
                                //The height was larger, so scale the width
                                dblScale  = (double)intSize / objImage.Height;
                                intHeight = intSize;
                                intWidth  = Convert.ToInt32(objImage.Width * dblScale);
                            }
                            else
                            {
                                //The width was larger, so scale the height
                                dblScale  = (double)intSize / objImage.Width;
                                intWidth  = intSize;
                                intHeight = Convert.ToInt32(objImage.Height * dblScale);
                            }

                            //create the thumbnail image
                            var objThumbnail = objImage.GetThumbnailImage(intWidth, intHeight, null, IntPtr.Zero);

                            //delete the old file ( if it exists )
                            if (File.Exists(strThumbnail))
                            {
                                File.Delete(strThumbnail);
                            }

                            //save the thumbnail image
                            objThumbnail.Save(strThumbnail, objImage.RawFormat);

                            //set the file attributes
                            File.SetAttributes(strThumbnail, FileAttributes.Normal);
                            File.SetLastWriteTime(strThumbnail, File.GetLastWriteTime(strImage));

                            //tidy up
                            objImage.Dispose();
                            objThumbnail.Dispose();
                        }
                        catch (Exception ex) //problem creating thumbnail
                        {
                            Logger.Error(ex);
                        }
                    }
                }
            }

            strThumbnail = Globals.ApplicationPath + "/" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\"));
            strThumbnail = strThumbnail.Replace("\\", "/");

            //return thumbnail filename
            return(strThumbnail);
        }
コード例 #3
0
ファイル: ContentManager.cs プロジェクト: Kr3m/FlatRedBall
        public T LoadFromFile <T>(string assetName)
        {
            string extension = FileManager.GetExtension(assetName);

            if (FileManager.IsRelative(assetName))
            {
                // get the absolute path using the current relative directory
                assetName = FileManager.RelativeDirectory + assetName;
            }



            string fullNameWithType = assetName + typeof(T).Name;


            // get the dictionary by the contentManagerName.  If it doesn't exist, GetDisposableDictionaryByName
            // will create it.

            if (mDisposableDictionary.ContainsKey(fullNameWithType))
            {
#if PROFILE
                mHistory.Add(new ContentLoadHistory(
                                 TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.Cached));
#endif

                return((T)mDisposableDictionary[fullNameWithType]);
            }
            else if (mNonDisposableDictionary.ContainsKey(fullNameWithType))
            {
                return((T)mNonDisposableDictionary[fullNameWithType]);
            }
            else
            {
#if PROFILE
                mHistory.Add(new ContentLoadHistory(
                                 TimeManager.CurrentTime,
                                 typeof(T).Name,
                                 fullNameWithType,
                                 ContentLoadDetail.HddFromFile));
#endif
#if DEBUG
                // The ThrowExceptionIfFileDoesntExist
                // call used to be done before the checks
                // in the dictionaries.  But whatever is held
                // in there may not really be a file so let's check
                // if the file exists after we check the dictionaries.
                FileManager.ThrowExceptionIfFileDoesntExist(assetName);
#endif

                IDisposable loadedAsset = null;

                if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Microsoft.Xna.Framework.Graphics.Texture2D))
                {
                    // for now we'll create it here, eventually have it in a dictionary:
                    loadedAsset = textureContentLoader.Load(assetName);
                }

                #region Scene

                else if (typeof(T) == typeof(FlatRedBall.Scene))
                {
                    FlatRedBall.Scene scene = FlatRedBall.Content.Scene.SceneSave.FromFile(assetName).ToScene(mName);

                    object sceneAsObject = scene;

                    lock (mNonDisposableDictionary)
                    {
                        if (!mNonDisposableDictionary.ContainsKey(fullNameWithType))
                        {
                            mNonDisposableDictionary.Add(fullNameWithType, scene);
                        }
                    }
                    return((T)sceneAsObject);
                }

                #endregion

                #region EmitterList

                else if (typeof(T) == typeof(EmitterList))
                {
                    EmitterList emitterList = EmitterSaveList.FromFile(assetName).ToEmitterList(mName);


                    mNonDisposableDictionary.Add(fullNameWithType, emitterList);


                    return((T)((object)emitterList));
                }

                #endregion

                #region Image
#if !MONOGAME
                else if (typeof(T) == typeof(Image))
                {
                    switch (extension.ToLowerInvariant())
                    {
                    case "gif":
                        Image image = Image.FromFile(assetName);
                        loadedAsset = image;
                        break;
                    }
                }
#endif
                #endregion

                #region BitmapList
#if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME
                else if (typeof(T) == typeof(BitmapList))
                {
                    loadedAsset = BitmapList.FromFile(assetName);
                }
#endif

                #endregion

                #region NodeNetwork
                else if (typeof(T) == typeof(NodeNetwork))
                {
                    NodeNetwork nodeNetwork = NodeNetworkSave.FromFile(assetName).ToNodeNetwork();

                    mNonDisposableDictionary.Add(fullNameWithType, nodeNetwork);

                    return((T)((object)nodeNetwork));
                }
                #endregion

                #region ShapeCollection

                else if (typeof(T) == typeof(ShapeCollection))
                {
                    ShapeCollection shapeCollection =
                        ShapeCollectionSave.FromFile(assetName).ToShapeCollection();

                    mNonDisposableDictionary.Add(fullNameWithType, shapeCollection);

                    return((T)((object)shapeCollection));
                }
                #endregion

                #region PositionedObjectList<Polygon>

                else if (typeof(T) == typeof(PositionedObjectList <FlatRedBall.Math.Geometry.Polygon>))
                {
                    PositionedObjectList <FlatRedBall.Math.Geometry.Polygon> polygons =
                        PolygonSaveList.FromFile(assetName).ToPolygonList();
                    mNonDisposableDictionary.Add(fullNameWithType, polygons);
                    return((T)((object)polygons));
                }

                #endregion

                #region AnimationChainList

                else if (typeof(T) == typeof(AnimationChainList))
                {
                    if (assetName.EndsWith("gif"))
                    {
#if WINDOWS_8 || UWP || DESKTOP_GL || STANDARD
                        throw new NotImplementedException();
#else
                        AnimationChainList acl = new AnimationChainList();
                        acl.Add(FlatRedBall.Graphics.Animation.AnimationChain.FromGif(assetName, this.mName));
                        acl[0].ParentGifFileName = assetName;
                        loadedAsset = acl;
#endif
                    }
                    else
                    {
                        loadedAsset =
                            AnimationChainListSave.FromFile(assetName).ToAnimationChainList(mName);
                    }

                    mNonDisposableDictionary.Add(fullNameWithType, loadedAsset);
                }

                #endregion

                else if (typeof(T) == typeof(Song))
                {
                    var loader = new SongLoader();
                    return((T)(object)loader.Load(assetName));
                }
#if MONOGAME
                else if (typeof(T) == typeof(SoundEffect))
                {
                    T soundEffect;

                    if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./"))
                    {
                        soundEffect = base.Load <T>(assetName.Substring(2));
                    }
                    else
                    {
                        soundEffect = base.Load <T>(assetName);
                    }

                    return(soundEffect);
                }
#endif

                #region RuntimeCsvRepresentation

#if !SILVERLIGHT
                else if (typeof(T) == typeof(RuntimeCsvRepresentation))
                {
#if XBOX360
                    throw new NotImplementedException("Can't load CSV from file.  Try instead to use the content pipeline.");
#else
                    return((T)((object)CsvFileManager.CsvDeserializeToRuntime(assetName)));
#endif
                }
#endif


                #endregion

                #region SplineList

                else if (typeof(T) == typeof(List <Spline>))
                {
                    List <Spline> splineList = SplineSaveList.FromFile(assetName).ToSplineList();
                    mNonDisposableDictionary.Add(fullNameWithType, splineList);
                    object asObject = splineList;

                    return((T)asObject);
                }

                else if (typeof(T) == typeof(SplineList))
                {
                    SplineList splineList = SplineSaveList.FromFile(assetName).ToSplineList();
                    mNonDisposableDictionary.Add(fullNameWithType, splineList);
                    object asObject = splineList;

                    return((T)asObject);
                }

                #endregion

                #region BitmapFont

                else if (typeof(T) == typeof(BitmapFont))
                {
                    // We used to assume the texture is named the same as the font file
                    // But now FRB understands the .fnt file and gets the PNG from the font file
                    //string pngFile = FileManager.RemoveExtension(assetName) + ".png";
                    string fntFile = FileManager.RemoveExtension(assetName) + ".fnt";

                    BitmapFont bitmapFont = new BitmapFont(fntFile, this.mName);

                    object bitmapFontAsObject = bitmapFont;

                    return((T)bitmapFontAsObject);
                }

                #endregion


                #region Text

                else if (typeof(T) == typeof(string))
                {
                    return((T)((object)FileManager.FromFileText(assetName)));
                }

                #endregion

                #region Catch mistakes

#if DEBUG
                else if (typeof(T) == typeof(Spline))
                {
                    throw new Exception("Cannot load Splines.  Try using the List<Spline> type instead.");
                }
                else if (typeof(T) == typeof(Emitter))
                {
                    throw new Exception("Cannot load Emitters.  Try using the EmitterList type instead.");
                }
#endif

                #endregion

                #region else, exception!

                else
                {
                    throw new NotImplementedException("Cannot load content of type " +
                                                      typeof(T).AssemblyQualifiedName + " from file.  If you are loading " +
                                                      "through the content pipeline be sure to remove the extension of the file " +
                                                      "name.");
                }

                #endregion

                if (loadedAsset != null)
                {
                    lock (mDisposableDictionary)
                    {
                        // Multiple threads could try to load this content simultaneously
                        if (!mDisposableDictionary.ContainsKey(fullNameWithType))
                        {
                            mDisposableDictionary.Add(fullNameWithType, loadedAsset);
                        }
                    }
                }

                return((T)loadedAsset);
            }
        }
コード例 #4
0
        /// <summary>
        /// Displays the images.
        /// </summary>
        public void DisplayImages()
        {
            string[] FilesArray       = ReturnFilesArray();
            string[] DirectoriesArray = ReturnDirectoriesArray();
            string   AppPath          = HttpContext.Current.Request.PhysicalApplicationPath;
            string   AppUrl;

            //Get the application's URL
            AppUrl = Request.ApplicationPath;
            if (!AppUrl.EndsWith("/"))
            {
                AppUrl += "/";
            }
            AppUrl = AppUrl.Replace("//", "/");

            GalleryPanel.Controls.Clear();
            if ((FilesArray == null || FilesArray.Length == 0) && (DirectoriesArray == null || DirectoriesArray.Length == 0))
            {
                gallerymessage.Text = NoImagesMessage + ": " + RootImagesFolder.Value;
            }
            else
            {
                string ImageFileName     = string.Empty;
                string ImageFileLocation = string.Empty;

                int thumbWidth  = 94;
                int thumbHeight = 94;

                if (CurrentImagesFolder.Value != RootImagesFolder.Value)
                {
                    HtmlImage myHtmlImage = new HtmlImage();
                    myHtmlImage.Src = Path.ApplicationRoot + "/DesktopModules/FCK/filemanager/folder.gif";
                    myHtmlImage.Attributes["unselectable"] = "on";
                    myHtmlImage.Attributes["align"]        = "absmiddle";
                    myHtmlImage.Attributes["vspace"]       = "36";

                    string ParentFolder = CurrentImagesFolder.Value.Substring(0, CurrentImagesFolder.Value.LastIndexOf("\\"));

                    Panel myImageHolder = new Panel();
                    myImageHolder.CssClass = "imageholder";
                    myImageHolder.Attributes["unselectable"] = "on";
                    myImageHolder.Attributes["onclick"]      = "divClick(this,'');";
                    myImageHolder.Attributes["ondblclick"]   = "gotoFolder('" + RootImagesFolder.Value + "','" + ParentFolder.Replace("\\", "\\\\") + "');";
                    myImageHolder.Controls.Add(myHtmlImage);

                    Panel myMainHolder = new Panel();
                    myMainHolder.CssClass = "imagespacer";
                    myMainHolder.Controls.Add(myImageHolder);

                    Panel myTitleHolder = new Panel();
                    myTitleHolder.CssClass = "titleHolder";
                    myTitleHolder.Controls.Add(new LiteralControl("Up"));
                    myMainHolder.Controls.Add(myTitleHolder);

                    GalleryPanel.Controls.Add(myMainHolder);
                }

                foreach (string _Directory in DirectoriesArray)
                {
                    try
                    {
                        string DirectoryName = _Directory.ToString();

                        HtmlImage myHtmlImage = new HtmlImage();
                        myHtmlImage.Src = Path.ApplicationRoot + "/DesktopModules/FCK/filemanager/folder.gif";
                        myHtmlImage.Attributes["unselectable"] = "on";
                        myHtmlImage.Attributes["align"]        = "absmiddle";
                        myHtmlImage.Attributes["vspace"]       = "29";

                        Panel myImageHolder = new Panel();
                        myImageHolder.CssClass = "imageholder";
                        myImageHolder.Attributes["unselectable"] = "on";
                        myImageHolder.Attributes["onclick"]      = "divClick(this);";
                        myImageHolder.Attributes["ondblclick"]   = "gotoFolder('" + RootImagesFolder.Value + "','" + DirectoryName.Replace(AppPath, string.Empty).Replace("\\", "\\\\") + "');";
                        myImageHolder.Controls.Add(myHtmlImage);

                        Panel myMainHolder = new Panel();
                        myMainHolder.CssClass = "imagespacer";
                        myMainHolder.Controls.Add(myImageHolder);

                        Panel myTitleHolder = new Panel();
                        myTitleHolder.CssClass = "titleHolder";
                        myTitleHolder.Controls.Add(new LiteralControl(DirectoryName.Replace(AppPath + CurrentImagesFolder.Value + "\\", string.Empty)));
                        myMainHolder.Controls.Add(myTitleHolder);

                        GalleryPanel.Controls.Add(myMainHolder);
                    }
                    catch
                    {
                        // nothing for error
                    }
                }

                foreach (string ImageFile in FilesArray)
                {
                    try
                    {
                        ImageFileName     = ImageFile.ToString();
                        ImageFileName     = ImageFileName.Substring(ImageFileName.LastIndexOf("\\") + 1);
                        ImageFileLocation = AppUrl;
//						ImageFileLocation = ImageFileLocation.Substring(ImageFileLocation.LastIndexOf("\\")+1);
                        //galleryfilelocation += "/";
                        ImageFileLocation += CurrentImagesFolder.Value;
                        ImageFileLocation += "/";
                        ImageFileLocation += ImageFileName;
                        ImageFileLocation  = ImageFileLocation.Replace("//", "/");
                        HtmlImage myHtmlImage = new HtmlImage();
                        myHtmlImage.Src = ImageFileLocation;
                        System.Drawing.Image myImage = Image.FromFile(ImageFile.ToString());
                        myHtmlImage.Attributes["unselectable"] = "on";
                        //myHtmlImage.border=0;

                        // landscape image
                        if (myImage.Width > myImage.Height)
                        {
                            if (myImage.Width > thumbWidth)
                            {
                                myHtmlImage.Width  = thumbWidth;
                                myHtmlImage.Height = Convert.ToInt32(myImage.Height * thumbWidth / myImage.Width);
                            }
                            else
                            {
                                myHtmlImage.Width  = myImage.Width;
                                myHtmlImage.Height = myImage.Height;
                            }
                            // portrait image
                        }
                        else
                        {
                            if (myImage.Height > thumbHeight)
                            {
                                myHtmlImage.Height = thumbHeight;
                                myHtmlImage.Width  = Convert.ToInt32(myImage.Width * thumbHeight / myImage.Height);
                            }
                            else
                            {
                                myHtmlImage.Width  = myImage.Width;
                                myHtmlImage.Height = myImage.Height;
                            }
                        }

                        if (myHtmlImage.Height < thumbHeight)
                        {
                            myHtmlImage.Attributes["vspace"] = Convert.ToInt32((thumbHeight / 2) - (myHtmlImage.Height / 2)).ToString();
                        }


                        Panel myImageHolder = new Panel();
                        myImageHolder.CssClass = "imageholder";
                        myImageHolder.Attributes["onclick"]    = "divClick(this,'" + ImageFileName + "');";
                        myImageHolder.Attributes["ondblclick"] = "returnImage('" + ImageFileLocation.Replace("\\", "/") + "','" + myImage.Width.ToString() + "','" + myImage.Height.ToString() + "');";
                        myImageHolder.Controls.Add(myHtmlImage);


                        Panel myMainHolder = new Panel();
                        myMainHolder.CssClass = "imagespacer";
                        myMainHolder.Controls.Add(myImageHolder);

                        Panel myTitleHolder = new Panel();
                        myTitleHolder.CssClass = "titleHolder";
                        myTitleHolder.Controls.Add(new LiteralControl(ImageFileName + "<BR>" + myImage.Width.ToString() + "x" + myImage.Height.ToString()));
                        myMainHolder.Controls.Add(myTitleHolder);

                        //GalleryPanel.Controls.Add(myImage);
                        GalleryPanel.Controls.Add(myMainHolder);

                        myImage.Dispose();
                    }
                    catch
                    {
                    }
                }
                gallerymessage.Text = string.Empty;
            }
        }
コード例 #5
0
        private void openFile_Click(object sender, EventArgs e)
        {
            char[,] braille2D = new char[, ] {
                //{ " el ", " ⠮ " },
                //{ " y ", " ⠯ " },
                //{ " de ", " ⠷ " },
                //{ " con ", " ⠾ " },
                //{ " en ", " ⠔ " },
                //{ " o ", " ⠖ " },
                //{ " para ", " ⠿ " },
                { ',', '⠠' },
                { '/', '⠌' },
                { '?', '⠹' },
                { '.', '⠨' },
                { 'á', '⠁' },
                { 'é', '⠑' },
                { 'í', '⠊' },
                { 'ó', '⠕' },
                { 'ú', '⠥' },
                { 'a', '⠁' },
                { 'b', '⠃' },
                { 'c', '⠉' },
                { 'd', '⠙' },
                { 'e', '⠑' },
                { 'f', '⠋' },
                { 'g', '⠛' },
                { 'h', '⠓' },
                { 'i', '⠊' },
                { 'j', '⠚' },
                { 'k', '⠅' },
                { 'l', '⠇' },
                { 'm', '⠍' },
                { 'ñ', '⠝' },
                { 'n', '⠝' },
                { 'o', '⠕' },
                { 'p', '⠏' },
                { 'q', '⠟' },
                { 'r', '⠗' },
                { 's', '⠎' },
                { 't', '⠞' },
                { 'u', '⠥' },
                { 'v', '⠧' },
                { 'w', '⠺' },
                { 'x', '⠭' },
                { 'y', '⠽' },
                { 'z', '⠵' },
                { 'A', '⠁' },
                { 'Á', '⠁' },
                { 'B', '⠃' },
                { 'C', '⠉' },
                { 'D', '⠙' },
                { 'E', '⠑' },
                { 'É', '⠑' },
                { 'F', '⠋' },
                { 'G', '⠛' },
                { 'H', '⠓' },
                { 'I', '⠊' },
                { 'Í', '⠊' },
                { 'J', '⠚' },
                { 'K', '⠅' },
                { 'L', '⠇' },
                { 'M', '⠍' },
                { 'N', '⠝' },
                { 'O', '⠕' },
                { 'Ó', '⠕' },
                { 'P', '⠏' },
                { 'Q', '⠟' },
                { 'R', '⠗' },
                { 'S', '⠎' },
                { 'T', '⠞' },
                { 'U', '⠥' },
                { 'Ú', '⠥' },
                { 'V', '⠧' },
                { 'W', '⠺' },
                { 'X', '⠭' },
                { 'Y', '⠽' },
                { 'Z', '⠵' },
                { '#', '⠼' },
                { '1', '⠂' },
                { '2', '⠆' },
                { '3', '⠲' },
                { '4', '⠲' },
                { '5', '⠢' },
                { '6', '⠖' },
                { '7', '⠶' },
                { '8', '⠦' },
                { '9', '⠔' },
                { '0', '⠴' },
                { ' ', ' ' }
            };


            //var fileContent = string.Empty;
            var filePath = string.Empty;

            using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
            {
                sb.Append("se crea openfiledialog\n");
                openFileDialog1.InitialDirectory = "c:\\";
                openFileDialog1.Filter           = "Image Files(*.png; *.jpg; *.bmp; *.gif)|*.png; *.jpg; *.bmp; *.gif";
                openFileDialog1.FilterIndex      = 2;
                openFileDialog1.RestoreDirectory = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    sb.Append("se abre openfile dialog\n");
                    //Get the path of specified file
                    filePath = openFileDialog1.FileName;

                    //Read the contents of the file into a stream
                    var fileStream = openFileDialog1.OpenFile();

                    //using (StreamReader reader = new StreamReader(fileStream))
                    //{
                    //    fileContent = reader.ReadToEnd();
                    //}
                }
            }


            if (filePath != null && filePath != "")
            {
                //sb.Append("se valida el filepath\n");
                MessageBox.Show("Imagen Cargada Correctamente", "Exito!", MessageBoxButtons.OK);
                pictureBox1.Image = Image.FromFile(filePath);

                var testImagePath = filePath;
                try
                {
                    //sb.Append("entra en try de tesseract\n");
                    using (var engine = new TesseractEngine(@"./tessdata", "spa", EngineMode.Default))
                    {
                        //sb.Append("entra en tesseract engine\n");
                        using (var img = Pix.LoadFromFile(testImagePath))
                        {
                            //sb.Append("usa pix para loadfromimage\n");
                            using (var page = engine.Process(img))
                            {
                                //sb.Append("hace engine process para path de imagen\n");
                                var text = page.GetText().TrimEnd();
                                //sb.Append("justo antes del for para replace\n");
                                for (int i = 0; i < 79; i++)
                                {
                                    //Console.WriteLine("indice de foreach: " + i);
                                    //Console.WriteLine("valor: " + braille2D[i, 0]);
                                    //Console.WriteLine("remplazo: " + braille2D[i, 1]);
                                    text = text.Replace(braille2D[i, 0], braille2D[i, 1]);
                                }
                                textBox1.Text = text;
                                var txtInput = Path.GetTempPath() + "log.txt";
                                File.WriteAllText(txtInput, text);
                                //sb.Append("se termina de escribir el output en un path temporal\n");
                                //File.AppendAllText("logger.txt", //sb.ToString());
                                //sb.Clear();
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    //sb.Append("Se encontro algun error durante el try tesseract\n"+ err.ToString()+"\n");
                    Trace.TraceError(err.ToString());
                    Console.WriteLine("Unexpected Error: " + err.Message);
                    Console.WriteLine("Details: ");
                    Console.WriteLine(err.ToString());
                    //File.AppendAllText("logger.txt", //sb.ToString());
                    //sb.Clear();
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerId"></param>
        /// <returns>Scanned images.</returns>
        public static string Scan(string scannerId)
        {
            var images       = new List <Image>();
            var hasMorePages = true;

            while (hasMorePages)
            {
                var manager = new DeviceManager();
                var device  = (from DeviceInfo info in manager.DeviceInfos where info.DeviceID == scannerId select info.Connect()).FirstOrDefault();

                if (device == null)
                {
                    // enumerate available devices
                    var availableDevices = manager.DeviceInfos.Cast <DeviceInfo>().Aggregate("", (current, info) => current + (info.DeviceID + "\n"));

                    // show error with available devices
                    throw new COMException("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }

                var item = device.Items[1];
                // scan image
                var wiaCommonDialog = new CommonDialogClass();
                var image           = new ImageFile();
                try
                {
                    image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP);

                    // save to temp file
                    var fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;

                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (COMException ex)
                {
                    const string message = "Error scanning image";
                    throw new WiaOperationException(message, ex);
                }
                finally
                {
                    item = null;
                    if (image != null)
                    {
                        Marshal.ReleaseComObject(image);
                    }
                    Marshal.ReleaseComObject(wiaCommonDialog);
                    //determine if there are any more pages waiting
                    Property documentHandlingSelect = null;
                    Property documentHandlingStatus = null;

                    foreach (Property prop in device.Properties)
                    {
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                        {
                            documentHandlingSelect = prop;
                        }

                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                        {
                            documentHandlingStatus = prop;
                        }
                    }

                    // assume there are no more pages
                    hasMorePages = false;

                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                }
            }

            return(new ImageToPdf
            {
                FitImagesToPage = true,
                ImageCompressionFormat = ImageFormat.MemoryBmp,
                PdfPageSize = PageSize.A4
            }.ExportToPdfAsBase64String(
                       images
                       ));
        }
コード例 #7
0
        private void showFiles()
        {
            if (this.ViewState["fpUploadFolderRelativePath"] == null)
            {
                this.ViewState["fpUploadFolderRelativePath"] = "";
            }
            if (this.ViewState["fpUploadFolderRelativePath"].ToString() != "")
            {
                this.Header.Text    = "C\x00e1c file bạn đ\x00e3 tải l\x00ean trong <b>" + this.ViewState["fpUploadFolderRelativePath"].ToString() + "</b>.";
                this.UpBtn.Visible  = true;
                this.GoRoot.Visible = true;
            }
            else
            {
                this.Header.Text    = "Xem nội dung <B>thư mục gốc.</b>";
                this.UpBtn.Visible  = false;
                this.GoRoot.Visible = false;
            }
            DirectoryInfo info = this.ValidatePath(this._UploadDir + ((string)this.ViewState["fpUploadFolderRelativePath"]));

            if (info != null)
            {
                if (this.Session[this.FPTextBoxID + "CurrentPageIndex"] != null)
                {
                    float num  = ((float)info.GetFileSystemInfos().Length) / ((float)this.dgFSList.PageSize);
                    int   num2 = (int)num;
                    if (num2 < num)
                    {
                        num2++;
                    }
                    if (((int)this.Session[this.FPTextBoxID + "CurrentPageIndex"]) < num2)
                    {
                        this.dgFSList.CurrentPageIndex = (int)this.Session[this.FPTextBoxID + "CurrentPageIndex"];
                    }
                    else
                    {
                        this.dgFSList.CurrentPageIndex = 0;
                    }
                }
                FileSystemInfo[] fileSystemInfos = info.GetFileSystemInfos();
                DataTable        table           = new DataTable();
                table.Columns.Add(new DataColumn("IsFile", Type.GetType("System.Boolean")));
                table.Columns.Add(new DataColumn("FileName", Type.GetType("System.String")));
                table.Columns.Add(new DataColumn("Size", Type.GetType("System.Int32")));
                table.Columns.Add(new DataColumn("imgWidth", Type.GetType("System.Int32")));
                table.Columns.Add(new DataColumn("imgHeight", Type.GetType("System.Int32")));
                table.Columns.Add(new DataColumn("Modified", Type.GetType("System.DateTime")));
                foreach (FileSystemInfo info2 in fileSystemInfos)
                {
                    DataRow row = table.NewRow();
                    string  str = info2.ToString();
                    row["FileName"] = info2.ToString();
                    string path = this._UploadDir + this.ViewState["fpUploadFolderRelativePath"].ToString() + "/" + str.Remove(0, str.LastIndexOf(@"\") + 1);
                    try
                    {
                        Image image = Image.FromFile(base.Server.MapPath(path));
                        row["imgWidth"]  = Convert.ToInt32(image.Width);
                        row["imgHeight"] = Convert.ToInt32(image.Height);
                        image.Dispose();
                    }
                    catch
                    {
                        row["imgWidth"]  = 0;
                        row["imgHeight"] = 0;
                    }
                    row["Modified"] = info2.LastWriteTime;
                    switch (info2.GetType().ToString())
                    {
                    case "System.IO.DirectoryInfo":
                        row["IsFile"] = false;
                        break;

                    case "System.IO.FileInfo":
                        row["IsFile"] = true;
                        row["Size"]   = ((FileInfo)info2).Length;
                        break;
                    }
                    table.Rows.Add(row);
                }
                DataView defaultView = table.DefaultView;
                defaultView.Sort         = ((string)this.ViewState["SortColumn"]) + " " + ((string)this.ViewState["SortOrder"]);
                this.dgFSList.DataSource = defaultView;
                if (this.ViewState["EditItemIndex"] != null)
                {
                    this.dgFSList.EditItemIndex = (int)this.ViewState["EditItemIndex"];
                }
                this.dgFSList.DataBind();
            }
        }
コード例 #8
0
 public Image CreateImage() => Image.FromFile(ImagePath);
コード例 #9
0
ファイル: Gif.cs プロジェクト: ajbadaj/AJut
        // =============[ Private Update Handlers ]================
        private static void HandlePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs <Uri> e)
        {
            if (!(d is ImageControl) || e.HasOldValue)
            {
                ClearGifInfo(d);
            }

            if (!e.HasNewValue)
            {
                return;
            }

            Stream imageStream = null;

            try
            {
                ImageStorage image = null;
                if (!e.NewValue.IsAbsoluteUri || e.NewValue.IsFile)
                {
                    image = ImageStorage.FromFile(e.NewValue.OriginalString);
                }
                else if (e.NewValue.Scheme.Equals("pack", StringComparison.InvariantCultureIgnoreCase))
                {
                    int      stopInd              = e.NewValue.AbsolutePath.IndexOf(';');
                    string   assemblyName         = e.NewValue.AbsolutePath.Substring(0, stopInd).Trim('/');
                    Assembly assembly             = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == assemblyName);
                    string   embeddedResourcePath = e.NewValue.AbsolutePath.Replace($"{assemblyName};component/", "").Trim('/');
                    embeddedResourcePath = FileHelpers.GenerateEmbeddedResourceName(embeddedResourcePath, assembly);

                    imageStream = assembly.GetManifestResourceStream(embeddedResourcePath);
                    if (imageStream != null)
                    {
                        image = ImageStorage.FromStream(imageStream);
                    }
                }
                else
                {
                    using (HttpWebResponse response = (HttpWebResponse)WebRequest.Create(e.NewValue).GetResponse())
                    {
                        using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            imageStream = new MemoryStream();
                            byte[] transferBuffer = reader.ReadBytes(1024);
                            while (transferBuffer.Length > 0)
                            {
                                imageStream.Write(transferBuffer, 0, transferBuffer.Length);
                                transferBuffer = reader.ReadBytes(1024);
                            }

                            image = ImageStorage.FromStream(imageStream);
                        }
                    }
                }

                SetCurrentFrameIndex(d, -1);
                SetInfo(d, new GifInfoCache(image));
                SetCurrentFrameIndex(d, 0);
                ResetTimer(d);
            }
            catch (Exception exception)
            {
                Logger.LogError(exception);
                ClearGifInfo(d);
            }
            finally
            {
                if (imageStream != null)
                {
                    imageStream.Close();
                    imageStream.Dispose();
                    imageStream = null;
                }
            }
        }