예제 #1
0
        private static void CopyImage(string file, ImageFileType type)
        {
            string newFileFullPath = Path.Combine(destFolder, Path.GetFileName(file));
            if (type == ImageFileType.Jpeg)
                newFileFullPath += ".jpg";
            else if (type == ImageFileType.Png)
                newFileFullPath += ".png";

            if (File.Exists(newFileFullPath))
                return;

            if (ImageHelper.IsMobileSizeImage(file))
                return;

            try
            {
                if (!Directory.Exists(destFolder))
                    Directory.CreateDirectory(destFolder);

                File.Copy(file, newFileFullPath);
            }
            catch (Exception)
            {
            }
        }
 public RasterImage(BitmapSource source, ImageFileType fileType)
 {
     this.source = source;
     this.fileType = fileType;
     this.frames = new List<IFrame>(1)
     {
         new RasterFrame(source)
     };
 }
예제 #3
0
 internal ImageSearchData(SearchData result, Uri refUrl, Uri refClkUrl, long fileSize, ImageFileType fileFormat, int height, int width, Uri tmbUrl, int tmbHeight, int tmbWidth)
     : base(result.Title, result.Description, result.Url, result.ClickUrl)
 {
     mRefererUrl = refUrl;
     mRefererClickUrl = refClkUrl;
     mFileSize = fileSize;
     mFileFormat = fileFormat;
     mHeight = height;
     mWidth = width;
     mThumbnail = new Thumbnail(tmbUrl, tmbHeight, tmbWidth);
 }
예제 #4
0
 public static void Capture( GraphicsDevice device, string filePath = null, ImageFileType format = ImageFileType.Png )
 {
     if( filePath == null )
     {
         if( !Directory.Exists( defaultFolder ) )
         {
             Directory.CreateDirectory( defaultFolder );
         }
         filePath = Path.Combine( defaultFolder, defaultName + "_" + ( FileCount( defaultFolder ) + 1 ).ToString() + "." + format.ToString().ToLower() );
     }
     device.BackBuffer.Save( filePath, format );
 }
예제 #5
0
		string GetFileType (ImageFileType type)
		{
			switch (type) {
			case ImageFileType.Bmp:
				return "bmp";
			case ImageFileType.Jpeg:
				return "jpeg";
			case ImageFileType.Png:
				return "png";
			default:
				throw new NotSupportedException ();
			}
		}
예제 #6
0
파일: RtfImage.cs 프로젝트: peterson1/ErrH
		internal RtfImage(string fileName, ImageFileType type)
		{
			_imgFname = fileName;
			_imgType = type;
			_alignment = Align.None;
			_margins = new Margins();
			_keepAspectRatio = true;
			_blockHead = @"{\pard";
			_blockTail = @"\par}";
			_startNewPage = false;
			
			Image image = Image.FromFile(fileName);
			_width = (image.Width / image.HorizontalResolution) * 72;
			_height = (image.Height / image.VerticalResolution) * 72;
		}
예제 #7
0
        public OutputSet(SourceImage owner, string name)
        {
            this.owner = owner;
            this.name = name;
            this.description = string.Empty;
            this.expanded = true;
            this.transformType = ImageTransformType.None;
            this.outputType = ImageHelpers.IsBitmapType(owner.Image.FileType)
                ? owner.Image.FileType
                : ImageFileType.DefaultRasterize;
            this.images = new ObservableCollection<OutputImage>();

            this.UpdateSize();

            owner.PropertyChanged += this.OnOwnerPropertyChanged;
        }
예제 #8
0
        /// <summary>
        /// Create a new image.
        /// </summary>
        /// <param name="Url">URL from where the image data can be fetched through a web browser (about 512 pixels).</param>
        /// <param name="Thumbnail">URL from where a thumbnail of the image can be fetched through a webbrowser (about 128 pixels).</param>
        /// <param name="Category">Describes what the image is used for.</param>
        /// <param name="Type">Image type like: gif, jpeg, png, svg.</param>
        /// <param name="Width">Width of the full scale image.</param>
        /// <param name="Height">Height of the full scale image.</param>
        public Image(Uri                Url,
                     Uri                Thumbnail,
                     ImageCategoryType  Category,
                     ImageFileType      Type,
                     UInt32             Width,
                     UInt32             Height)
        {
            #region Initial checks

            if (Url == null)
                throw new ArgumentNullException("Url", "The given parameter must not be null!");

            #endregion

            this._Url        = Url;
            this._Thumbnail  = Thumbnail;
            this._Category   = Category;
            this._Type       = Type;
            this._Width      = Width;
            this._Height     = Height;
        }
        /// <exception cref="ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        internal string SearchGalleryAdvancedRequest(string url,
            string qAll = null, string qAny = null,
            string qExactly = null, string qNot = null,
            ImageFileType? fileType = null, ImageSize? imageSize = null)
        {
            if (string.IsNullOrWhiteSpace(url))
                throw new ArgumentNullException(nameof(url));

            if (string.IsNullOrWhiteSpace(qAll) &&
                string.IsNullOrWhiteSpace(qAny) &&
                string.IsNullOrWhiteSpace(qExactly) &&
                string.IsNullOrWhiteSpace(qNot))
                throw new ArgumentNullException(null,
                    "At least one search parameter must be provided (All | Any | Exactly | Not).");

            var query = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(qAll))
                query.Append($"&q_all={WebUtility.UrlEncode(qAll)}");

            if (!string.IsNullOrWhiteSpace(qAny))
                query.Append($"&q_any={WebUtility.UrlEncode(qAny)}");

            if (!string.IsNullOrWhiteSpace(qExactly))
                query.Append($"&q_exactly={WebUtility.UrlEncode(qExactly)}");

            if (!string.IsNullOrWhiteSpace(qNot))
                query.Append($"&q_not={WebUtility.UrlEncode(qNot)}");

            if (fileType != null)
                query.Append($"&q_type={WebUtility.UrlEncode(fileType.ToString().ToLower())}");

            if (imageSize != null)
                query.Append($"&q_size_px={WebUtility.UrlEncode(imageSize.ToString().ToLower())}");

            return $"{url}?{query}".Replace("?&", "?");
        }
예제 #10
0
        public string GetScaledPath(double scale, string fileNameOverride = null, ImageFileType fileTypeOverride = ImageFileType.None)
        {
            string path;
            int insertPos = -1;

            if (string.IsNullOrEmpty(fileNameOverride))
            {
                path = this.pathScaleLength > 0
                    ? this.path.Remove(this.pathScaleStart, this.pathScaleLength - 1)
                    : this.path;

                insertPos = this.pathScaleStart;
            }
            else
            {
                path = Path.Combine(this.FullDir, fileNameOverride);
                insertPos = path.Length - Path.GetExtension(path).Length;
            }

            if (insertPos != -1 && scale > 0)
            {
                path = path.Insert(insertPos, $".scale-{(int)(scale * 100.0)}");
            }

            if (fileTypeOverride != ImageFileType.None && fileTypeOverride != this.Image.FileType)
            {
                string oldExtension = Path.GetExtension(path);
                string newExtension = oldExtension;

                switch (fileTypeOverride)
                {
                    case ImageFileType.Bmp:
                        newExtension = ".bmp";
                        break;

                    case ImageFileType.Jpeg:
                        newExtension = ".jpg";
                        break;

                    case ImageFileType.Png:
                        newExtension = ".png";
                        break;

                    default:
                        Debug.Fail("Can't save with file extension for: " + fileTypeOverride);
                        break;
                }

                if (oldExtension != newExtension)
                {
                    path = path.Remove(path.Length - oldExtension.Length, oldExtension.Length) + newExtension;
                }
            }

            return path;
        }
예제 #11
0
파일: TestImage.cs 프로젝트: releed/paradox
        public void TestLoadAndSave()
        {
            var dxsdkDir = Environment.GetEnvironmentVariable("DXSDK_DIR");

            if (string.IsNullOrEmpty(dxsdkDir))
                throw new NotSupportedException("Install DirectX SDK June 2010 to run this test (DXSDK_DIR env variable is missing).");

            GC.Collect();
            GC.WaitForFullGCComplete();
            testMemoryBefore = GC.GetTotalMemory(true);

            var files = new List<string>();
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.dds", SearchOption.AllDirectories));
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.jpg", SearchOption.AllDirectories));
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.bmp", SearchOption.AllDirectories));

            const int Count = 1; // Change this to perform memory benchmarks
            var types = new ImageFileType[] {
                ImageFileType.Dds,
            };

            for (int i = 0; i < Count; i++)
            {
                for (int j = 0; j < types.Length; j++)
                {
                    Console.Write("[{0}] ", i);
                    ProcessFiles(files, types[j]);
                }
            }
        }
예제 #12
0
파일: WICHelper.cs 프로젝트: numo16/SharpDX
 private static Guid GetContainerFormatFromFileType(ImageFileType fileType)
 {
     switch (fileType)
     {
         case ImageFileType.Bmp:
             return ContainerFormatGuids.Bmp;
         case ImageFileType.Jpg:
             return ContainerFormatGuids.Jpeg;
         case ImageFileType.Gif:
             return ContainerFormatGuids.Gif;
         case ImageFileType.Png:
             return ContainerFormatGuids.Png;
         case ImageFileType.Tiff:
             return ContainerFormatGuids.Tiff;
         case ImageFileType.Wmp:
             return ContainerFormatGuids.Wmp;
         default:
             throw new NotSupportedException("Format not supported");
     }
 }
예제 #13
0
파일: Image.cs 프로젝트: rbwhitaker/SharpDX
 /// <summary>
 /// Saves this instance to a stream.
 /// </summary>
 /// <param name="imageStream">The destination stream.</param>
 /// <param name="fileType">Specify the output format.</param>
 /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
 public void Save(Stream imageStream, ImageFileType fileType)
 {
     Save(pixelBuffers, this.pixelBuffers.Length, Description, imageStream, fileType);
 }
예제 #14
0
 public abstract void SaveToStream(object backend, System.IO.Stream stream, ImageFileType fileType);
예제 #15
0
		public override void SaveToStream (object backend, System.IO.Stream stream, ImageFileType fileType)
		{
			var pix = (GtkImage)backend;
			var buffer = pix.Frames[0].Pixbuf.SaveToBuffer (GetFileType (fileType));
			stream.Write (buffer, 0, buffer.Length);
		}
예제 #16
0
파일: Image.cs 프로젝트: Julyuary/paradox
 /// <summary>
 /// Saves this instance to a stream.
 /// </summary>
 /// <param name="imageStream">The destination stream.</param>
 /// <param name="fileType">Specify the output format.</param>
 /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
 public void Save(Stream imageStream, ImageFileType fileType)
 {
     if (imageStream == null) throw new ArgumentNullException("imageStream");
     Save(pixelBuffers, this.pixelBuffers.Length, Description, imageStream, fileType);
 }
예제 #17
0
 public LoadSaveDelegate(ImageFileType fileType, ImageLoadDelegate load, ImageSaveDelegate save)
 {
     FileType = fileType;
     Load     = load;
     Save     = save;
 }
예제 #18
0
 /// <summary>
 /// Saves this instance to a stream.
 /// </summary>
 /// <param name="pixelBuffers">The buffers to save.</param>
 /// <param name="count">The number of buffers to save.</param>
 /// <param name="description">Global description of the buffer.</param>
 /// <param name="imageStream">The destination stream.</param>
 /// <param name="fileType">Specify the output format.</param>
 /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
 internal static void Save(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFileType fileType)
 {
     foreach (var loadSaveDelegate in loadSaveDelegates)
     {
         if (loadSaveDelegate.FileType == fileType)
         {
             loadSaveDelegate.Save(pixelBuffers, count, description, imageStream);
             return;
         }
     }
     throw new NotSupportedException("This file format is not yet implemented.");
 }
예제 #19
0
 /// <summary>
 /// Saves this instance to a stream.
 /// </summary>
 /// <param name="imageStream">The destination stream.</param>
 /// <param name="fileType">Specify the output format.</param>
 /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
 public void Save(Stream imageStream, ImageFileType fileType)
 {
     Save(pixelBuffers, this.pixelBuffers.Length, Description, imageStream, fileType);
 }
예제 #20
0
 private static void SaveToWICMemory(PixelBuffer[] pixelBuffer, int count, WICFlags flags, ImageFileType fileType, Stream stream)
 {
     if (count > 1)
     {
         EncodeMultiframe(pixelBuffer, count, flags, GetContainerFormatFromFileType(fileType), stream);
     }
     else
     {
         EncodeSingleFrame(pixelBuffer[0], flags, GetContainerFormatFromFileType(fileType), stream);
     }
 }
예제 #21
0
        private void ProcessFiles(Game game, ImageFileType sourceFormat, ImageFileType intermediateFormat)
        {
            var testMemoryBefore = GC.GetTotalMemory(true);

            Log.Info("Testing {0}", intermediateFormat);
            Console.Out.Flush();
            var imageCount = 0;
            var clock      = Stopwatch.StartNew();

            // Load an image from a file and dispose it.
            var   fileName = sourceFormat.ToFileExtension().Substring(1) + "Image";
            var   filePath = "ImageTypes/" + fileName;
            Image image;

            using (var inStream = game.Content.OpenAsStream(filePath, StreamFlags.None))
                image = Image.Load(inStream);
            image.Dispose();

            // Load an image from a buffer
            byte[] buffer;
            using (var inStream = game.Content.OpenAsStream(filePath, StreamFlags.None))
            {
                var bufferSize = inStream.Length;
                buffer = new byte[bufferSize];
                inStream.Read(buffer, 0, (int)bufferSize);
            }

            using (image = Image.Load(buffer))
            {
                // Write this image to a memory stream using DDS format.
                var tempStream = new MemoryStream();
                image.Save(tempStream, intermediateFormat);
                tempStream.Position = 0;

                // Save to a file on disk
                var extension = intermediateFormat.ToFileExtension();
                using (var outStream = VirtualFileSystem.ApplicationCache.OpenStream(fileName + extension, VirtualFileMode.Create, VirtualFileAccess.Write))
                    image.Save(outStream, intermediateFormat);

                if (intermediateFormat == ImageFileType.Xenko || intermediateFormat == ImageFileType.Dds || (sourceFormat == intermediateFormat &&
                                                                                                             intermediateFormat != ImageFileType.Gif)) // TODO: remove this when Giff compression/decompression is fixed
                {
                    int allowSmallDifferences;
                    switch (intermediateFormat)
                    {
                    case ImageFileType.Tiff:    // TODO: remove this when tiff encryption implementation is stable
                    case ImageFileType.Png:     // TODO: remove this when png  encryption implementation is stable
                        allowSmallDifferences = 1;
                        break;

                    case ImageFileType.Jpg:     // TODO: remove this when jepg encryption implementation is stable
                        allowSmallDifferences = 30;
                        break;

                    default:
                        allowSmallDifferences = 0;
                        break;
                    }

                    // Reload the image from the memory stream.
                    var image2 = Image.Load(tempStream);
                    CompareImage(image, image2, false, allowSmallDifferences, fileName);
                    image2.Dispose();
                }
            }

            imageCount++;

            var time = clock.ElapsedMilliseconds;

            clock.Stop();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            var testMemoryAfter = GC.GetTotalMemory(true);

            Log.Info("Loaded {0} and convert to (Dds, Jpg, Png, Gif, Bmp, Tiff) image from DirectXSDK test Memory: {1} bytes, in {2}ms", imageCount, testMemoryAfter - testMemoryBefore, time);
        }
        public override void SaveToStream(object backend, Stream stream, ImageFileType fileType)
        {
            var img = (DroidImage)backend;

            img.SaveToStream(stream, fileType);
        }
예제 #23
0
        /// <summary>
        ///     Creates the thumbnail image.
        /// </summary>
        /// <param name="originalImageEntity">The original image entity.</param>
        /// <param name="thumbnailWidth">Width of the thumbnail.</param>
        /// <param name="thumbnailHeight">Height of the thumbnail.</param>
        /// <param name="scaleEnumAlias">The scale enum alias.</param>
        /// <returns></returns>
        private Stream CreateThumbnailImage(ImageFileType originalImageEntity, int thumbnailWidth, int thumbnailHeight, string scaleEnumAlias)
        {
            // No thumbnail was found.
            // Need to create one
            var thumbnailImageMemoryStream = new MemoryStream( );

            // Get the original image from the database
            using (Stream imageDataStream = GetImageDataStream(originalImageEntity.Id))
            {
                using (Image originalImage = Image.FromStream(imageDataStream))
                {
                    using (Image thumbnailImage = new Bitmap(thumbnailWidth, thumbnailHeight))
                    {
                        using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailImage))
                        {
                            switch (scaleEnumAlias)
                            {
                            case "core:scaleImageToFit":
                                thumbnailGraphics.CompositingQuality = CompositingQuality.HighQuality;
                                thumbnailGraphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                thumbnailGraphics.SmoothingMode      = SmoothingMode.HighQuality;
                                thumbnailGraphics.DrawImage(originalImage, new Rectangle(0, 0, thumbnailWidth, thumbnailHeight));
                                break;

                            case "core:scaleImageProportionally":
                                // Get the smaller of the ratio between height and width
                                double aspectRatioWidth  = thumbnailWidth / ( double )originalImage.Width;
                                double aspectRatioHeight = thumbnailHeight / ( double )originalImage.Height;
                                double aspectRatio       = aspectRatioWidth < aspectRatioHeight ? aspectRatioWidth : aspectRatioHeight;

                                // Calculate the target rectangle
                                var targetRectangle = new Rectangle
                                {
                                    X      = ( int )((thumbnailWidth - (originalImage.Width * aspectRatio)) / 2),
                                    Y      = ( int )((thumbnailHeight - (originalImage.Height * aspectRatio)) / 2),
                                    Width  = ( int )(originalImage.Width * aspectRatio),
                                    Height = ( int )(originalImage.Height * aspectRatio)
                                };

                                // Calculate the source rectangle
                                var sourceRectangle = new Rectangle
                                {
                                    X      = 0,
                                    Y      = 0,
                                    Width  = originalImage.Width,
                                    Height = originalImage.Height
                                };

                                thumbnailGraphics.Clear(Color.Transparent);
                                thumbnailGraphics.CompositingQuality = CompositingQuality.HighQuality;
                                thumbnailGraphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                thumbnailGraphics.SmoothingMode      = SmoothingMode.HighQuality;
                                thumbnailGraphics.DrawImage(originalImage, targetRectangle, sourceRectangle, GraphicsUnit.Pixel);
                                break;

                            case "core:cropImage":
                                thumbnailGraphics.DrawImageUnscaled(originalImage, new Rectangle(0, 0, thumbnailWidth, thumbnailHeight));
                                break;
                            }
                        }

                        // Save the thumbnail as the same format as the original
                        thumbnailImage.Save(thumbnailImageMemoryStream, originalImage.RawFormat);
                    }
                }
            }

            return(thumbnailImageMemoryStream);
        }
예제 #24
0
 public void Save(Stream stream, ImageFileType fileType)
 {
     ToolkitEngine.ImageBackendHandler.SaveToStream (ToBitmap ().Backend, stream, fileType);
 }
예제 #25
0
파일: Image.cs 프로젝트: Julyuary/paradox
 public LoadSaveDelegate(ImageFileType fileType, ImageLoadDelegate load, ImageSaveDelegate save)
 {
     FileType = fileType;
     Load = load;
     Save = save;
 }
예제 #26
0
 public void Save(string file, ImageFileType fileType)
 {
     using (var f = File.OpenWrite(file))
         Save(f, fileType);
 }
예제 #27
0
        /// <summary>
        /// Request a screenshot and save it to disc.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <param name="screenShotUrl">The screenshot URL.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <param name="depthBufferFormat">The depth buffer format.</param>
        /// <param name="fileType">Type of the file.</param>
        /// <returns>
        /// True on success
        /// </returns>
        public static bool SaveScreenshot(GameBase game, string screenshotUrl, int width, int height, PixelFormat pixelFormat = PixelFormat.R8G8B8A8_UNorm, PixelFormat depthBufferFormat = PixelFormat.D24_UNorm_S8_UInt, ImageFileType fileType = ImageFileType.Png)
        {
            var status            = true;
            var graphicsContext   = game.GraphicsContext;
            var graphicsDevice    = game.GraphicsDevice;
            var commandList       = graphicsContext.CommandList;
            var gameSystems       = game.GameSystems;
            var drawTime          = game.DrawTime;
            var previousPresenter = graphicsDevice.Presenter;

            try
            {
                // set the master output
                var renderTarget = graphicsContext.Allocator.GetTemporaryTexture2D(width, height, pixelFormat, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
                var depthStencil = graphicsContext.Allocator.GetTemporaryTexture2D(width, height, depthBufferFormat, TextureFlags.DepthStencil);

                var tempPresenter = new RenderTargetGraphicsPresenter(graphicsDevice, renderTarget, depthStencil.ViewFormat);

                try
                {
                    // temp presenter
                    graphicsDevice.Presenter = tempPresenter;

                    // Always clear the state of the GraphicsDevice to make sure a scene doesn't start with a wrong setup
                    commandList.ClearState();

                    // render the screenshot
                    graphicsContext.ResourceGroupAllocator.Reset(graphicsContext.CommandList);
                    gameSystems.Draw(drawTime);

                    // write the screenshot to the file
                    renderTarget.SaveTexture(commandList, screenshotUrl, fileType);
                }
                finally
                {
                    // Cleanup
                    graphicsDevice.Presenter = previousPresenter;
                    tempPresenter.Dispose();

                    graphicsContext.Allocator.ReleaseReference(depthStencil);
                    graphicsContext.Allocator.ReleaseReference(renderTarget);
                }
            }
            catch (Exception e)
            {
                status = false;
            }

            return(status);
        }
예제 #28
0
 public void Save(Stream stream, ImageFileType fileType)
 {
     ToolkitEngine.ImageBackendHandler.SaveToStream(ToBitmap().Backend, stream, fileType);
 }
예제 #29
0
 public bool ImageFileType(ImageFileType imageFileType)
 {
     return(imageFileType == Enums.ImageFileType.Jpg);
 }
예제 #30
0
        private ImageSearchData ToBossImageSearchResult(XParseElement node)
        {
            SearchData result = this.ToSearchResult(node);

            if (result != null)
            {
                Uri           refererUrl                  = null;
                Uri           refererClickUrl             = null;
                Uri           tmbUrl                      = null;
                ImageFileType fileFormat                  = default(ImageFileType);
                long          size                        = 0;
                int           height                      = 0;
                int           width                       = 0;
                int           tmbHeight                   = 0;
                int           tmbWidth                    = 0;
                System.Globalization.CultureInfo convCult = new System.Globalization.CultureInfo("en-US");


                foreach (XParseElement prpNode in node.Elements())
                {
                    switch (prpNode.Name.LocalName)
                    {
                    case "refererurl":
                        refererUrl = new Uri(prpNode.Value);
                        break;

                    case "refererclickurl":
                        refererClickUrl = new Uri(prpNode.Value);
                        break;

                    case "size":
                        double srcSize = 0;
                        if (prpNode.Value.EndsWith("Bytes"))
                        {
                            double.TryParse(prpNode.Value.Replace("Bytes", ""), System.Globalization.NumberStyles.Any, convCult, out srcSize);
                        }
                        else if (prpNode.Value.EndsWith("KB"))
                        {
                            double.TryParse(prpNode.Value.Replace("KB", ""), System.Globalization.NumberStyles.Any, convCult, out srcSize);
                            srcSize *= 1024;
                        }
                        else if (prpNode.Value.EndsWith("MB"))
                        {
                            double.TryParse(prpNode.Value.Replace("MB", ""), System.Globalization.NumberStyles.Any, convCult, out srcSize);
                            srcSize *= Math.Pow(1024, 2);
                        }
                        size = Convert.ToInt64(srcSize);
                        break;

                    case "format":
                        switch (prpNode.Value.ToLower())
                        {
                        case "bmp":
                            fileFormat = ImageFileType.Bmp;
                            break;

                        case "gif":
                            fileFormat = ImageFileType.Gif;
                            break;

                        case "jpg":
                            fileFormat = ImageFileType.Jpeg;
                            break;

                        case "jpeg":
                            fileFormat = ImageFileType.Jpeg;
                            break;

                        case "png":
                            fileFormat = ImageFileType.Png;
                            break;

                        default:
                            fileFormat = ImageFileType.Any;
                            break;
                        }
                        break;

                    case "height":
                        int.TryParse(prpNode.Value, out height);
                        break;

                    case "width":
                        int.TryParse(prpNode.Value, out width);
                        break;

                    case "thumbnailurl":
                        if (prpNode.Value != string.Empty)
                        {
                            tmbUrl = new Uri(prpNode.Value);
                        }
                        break;

                    case "thumbnailwidth":
                        int.TryParse(prpNode.Value, out tmbWidth);
                        break;

                    case "thumbnailheight":
                        int.TryParse(prpNode.Value, out tmbHeight);
                        break;
                    }
                }

                return(new ImageSearchData(result, refererUrl, refererClickUrl, size, fileFormat, height, width, tmbUrl, tmbHeight, tmbWidth));
            }
            else
            {
                return(null);
            }
        }
예제 #31
0
파일: Image.cs 프로젝트: rbwhitaker/SharpDX
 /// <summary>
 /// Saves this instance to a file.
 /// </summary>
 /// <param name="fileName">The destination file.</param>
 /// <param name="fileType">Specify the output format.</param>
 /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
 public void Save(string fileName, ImageFileType fileType)
 {
     using (var imageStream = new NativeFileStream(fileName, NativeFileMode.Create, NativeFileAccess.Write))
     {
         Save(imageStream, fileType);
     }
 }
예제 #32
0
 public async Task <string> Save(string filePath, string outputFolder, ImageFileType type)
 {
     throw new NotImplementedException();
 }
예제 #33
0
        private static void imageToPdf(Stream streamToConvert, Stream resultStream, ImageFileType imageFileType)
        {
            var pdfDocument = new Pdf();
            var pdfDocumentSection = pdfDocument.Sections.Add();

            var image = new Image(pdfDocumentSection)
            {
                ImageInfo =
                                    {
                                        ImageFileType = imageFileType,
                                        ImageStream = streamToConvert
                                    }
            };

            pdfDocumentSection.Paragraphs.Add(image);

            pdfDocument.Save(resultStream);
            streamToConvert.Close();
        }
예제 #34
0
        public void TestLoadAndSave()
        {

            GC.Collect();
            GC.WaitForFullGCComplete();
            testMemoryBefore = GC.GetTotalMemory(true);

            var files = new List<string>();
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.dds", SearchOption.AllDirectories));
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.jpg", SearchOption.AllDirectories));
            files.AddRange(Directory.EnumerateFiles(Path.Combine(dxsdkDir, @"Samples\Media"), "*.bmp", SearchOption.AllDirectories));

            const int Count = 1; // Change this to perform memory benchmarks
            var types = new ImageFileType[] {
                ImageFileType.Dds,
                ImageFileType.Jpg,
                ImageFileType.Png,
                ////ImageFileType.Gif,
                ////ImageFileType.Bmp,
                ImageFileType.Tiff,
                ImageFileType.Tktx,
            };

            for (int i = 0; i < Count; i++)
            {
                for (int j = 0; j < types.Length; j++)
                {
                    Console.Write("[{0}] ", i);
                    ProcessFiles(files, types[j]);
                }
            }
        }
예제 #35
0
파일: WICHelper.cs 프로젝트: numo16/SharpDX
 private static void SaveToWICMemory(PixelBuffer[] pixelBuffer, int count, WICFlags flags, ImageFileType fileType, Stream stream)
 {
     if (count > 1)
         EncodeMultiframe(pixelBuffer, count, flags, GetContainerFormatFromFileType(fileType), stream);
     else
         EncodeSingleFrame(pixelBuffer[0], flags, GetContainerFormatFromFileType(fileType), stream);
 }
예제 #36
0
 public abstract void SaveToStream(object backend, System.IO.Stream stream, ImageFileType fileType);
예제 #37
0
파일: TestImage.cs 프로젝트: releed/paradox
        private void ProcessFiles(IEnumerable<string> files, ImageFileType intermediateFormat)
        {

            Console.WriteLine("Testing {0}", intermediateFormat);
            Console.Out.Flush();
            int imageCount = 0;
            var clock = Stopwatch.StartNew();
            foreach (var file in files)
            {
                // Load an image from a file and dispose it.
                Image image;
                using (var inStream = File.OpenRead(file))
                    image = Image.Load(inStream);
                image.Dispose();

                // Load an image from a buffer
                var buffer = File.ReadAllBytes(file);

                using (image = Image.Load(buffer))
                {

                    // Write this image to a memory stream using DDS format.
                    var tempStream = new MemoryStream();
                    image.Save(tempStream, intermediateFormat);
                    tempStream.Position = 0;

                    // Save to a file on disk
                    var name = Enum.GetName(typeof(ImageFileType), intermediateFormat).ToLower();
                    using (var outStream = File.OpenWrite(Path.ChangeExtension(Path.GetFileName(file), name)))
                        image.Save(outStream, intermediateFormat);

                    if (intermediateFormat == ImageFileType.Dds)
                    {
                        // Reload the image from the memory stream.
                        var image2 = Image.Load(tempStream);
                        CompareImage(image, image2, file);
                        image2.Dispose();
                    }
                }

                imageCount++;
            }
            var time = clock.ElapsedMilliseconds;
            clock.Stop();

            GC.Collect();
            GC.WaitForPendingFinalizers();
            var testMemoryAfter = GC.GetTotalMemory(true);
            Console.WriteLine("Loaded {0} and convert to (Dds, Jpg, Png, Gif, Bmp, Tiff) image from DirectXSDK test Memory: {1} bytes, in {2}ms", imageCount, testMemoryAfter - testMemoryBefore, time);
        }
예제 #38
0
        public HttpResponseMessage GetImageThumbnail(string imageId, string sizeId, string scaleId)
        {
            using (Profiler.Measure("ImageController.GetImageThumbnail"))
            {
                EntityRef imageIdRef = WebApiHelpers.GetIdWithDashedAlias(imageId);
                EntityRef sizeIdRef  = WebApiHelpers.GetIdWithDashedAlias(sizeId);
                EntityRef scaleIdRef = WebApiHelpers.GetIdWithDashedAlias(scaleId);

                var imageInterface = new ImageInterface();
                imageInterface.PreloadImageThumbnail(imageIdRef);

                ImageFileType thumbnailImage = imageInterface.GetImageThumbnail(imageIdRef, sizeIdRef, scaleIdRef);

                if (thumbnailImage == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                string dataHash = thumbnailImage.FileDataHash;
                // Get the entity tag, which is the hash of the image data + dimensions + scaling
                string etag = string.Format("\"{0}\"", imageInterface.GetImageThumbnailETag(dataHash, sizeIdRef, scaleIdRef));

                // If the request contains the same e-tag then return a not modified
                if (Request.Headers.IfNoneMatch != null &&
                    Request.Headers.IfNoneMatch.Any(et => et.Tag == etag))
                {
                    var notModifiedResponse = new HttpResponseMessage(HttpStatusCode.NotModified);
                    notModifiedResponse.Headers.ETag         = new EntityTagHeaderValue(etag, false);
                    notModifiedResponse.Headers.CacheControl = new CacheControlHeaderValue
                    {
                        MustRevalidate = true,
                        MaxAge         = GetCacheMaxAge( )
                    };
                    return(notModifiedResponse);
                }

                Stream imageDataStream;

                try
                {
                    imageDataStream = imageInterface.GetImageDataStream(dataHash);
                }
                catch (FileNotFoundException)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                if (imageDataStream == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                // Return the image
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(imageDataStream)
                };
                response.Headers.ETag         = new EntityTagHeaderValue(etag, false);
                response.Headers.CacheControl = new CacheControlHeaderValue
                {
                    MustRevalidate = true,
                    MaxAge         = GetCacheMaxAge( )
                };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetImageMediaType(thumbnailImage.FileExtension));

                return(response);
            }
        }
예제 #39
0
 public void Save(string file, ImageFileType fileType)
 {
     using (var f = File.OpenWrite (file))
         Save (f, fileType);
 }
예제 #40
0
		/// <summary>
		/// Add an image to this container.
		/// </summary>
		/// <param name="imgFname">Filename of the image.</param>
		/// <param name="imgType">File type of the image.</param>
		/// <returns>Image being added.</returns>
		public RtfImage addImage(string imgFname, ImageFileType imgType)
		{
			if (!_allowImage) {
				throw new Exception("Image is not allowed.");
			}
			RtfImage block = new RtfImage(imgFname, imgType);
			addBlock(block);
			return block;
		}
예제 #41
0
        /// <summary>
        /// Gets an array of valid file extensions used by iView.NET, specified by
        /// the image file type enumeration.
        /// </summary>
        /// <param name="nImageType">Specifies the type of file extensions to return.</param>
        /// <returns></returns>
        public static string[] GetFileExtensions(ImageFileType nImageType)
        {
            switch (nImageType)
            {
                case ImageFileType.All:
                    return new string[] { BMP, GIF, ICON, JPE, JPG, JPEG, PNG, TIF, TIFF };
                case ImageFileType.Bmp:
                    return new string[] { BMP };
                case ImageFileType.Gif:
                    return new string[] { GIF };
                case ImageFileType.Icon:
                    return new string[] { ICON };
                case ImageFileType.Jpeg:
                    return new string[] { JPE, JPG, JPEG };
                case ImageFileType.Png:
                    return new string[] { PNG };
                case ImageFileType.Tiff:
                    return new string[] { TIF, TIFF };
            }

            return null;
        }
예제 #42
0
        public override void SaveToStream(object backend, System.IO.Stream stream, ImageFileType fileType)
        {
            NSImage img = backend as NSImage;
            if (img == null)
                throw new NotSupportedException ();

            var imageData = img.AsTiff ();
            var imageRep = (NSBitmapImageRep) NSBitmapImageRep.ImageRepFromData (imageData);
            var props = new NSDictionary ();
            imageData = imageRep.RepresentationUsingTypeProperties (fileType.ToMacFileType (), props);
            using (var s = imageData.AsStream ()) {
                s.CopyTo (stream);
            }
        }
예제 #43
0
파일: Image.cs 프로젝트: Julyuary/paradox
        /// <summary>
        /// Registers a loader/saver for a specified image file type.
        /// </summary>
        /// <param name="type">The file type (use integer and explicit casting to <see cref="ImageFileType"/> to register other fileformat.</param>
        /// <param name="loader">The loader delegate (can be null).</param>
        /// <param name="saver">The saver delegate (can be null).</param>
        /// <exception cref="System.ArgumentException"></exception>
        public static void Register(ImageFileType type, ImageLoadDelegate loader, ImageSaveDelegate saver)
        {
            // If reference equals, then it is null
            if (ReferenceEquals(loader, saver))
                throw new ArgumentNullException("Can set both loader and saver to null", "loader/saver");

            var newDelegate = new LoadSaveDelegate(type, loader, saver);
            for (int i = 0; i < loadSaveDelegates.Count; i++)
            {
                var loadSaveDelegate = loadSaveDelegates[i];
                if (loadSaveDelegate.FileType == type)
                {
                    loadSaveDelegates[i] = newDelegate;
                    return;
                }
            }
            loadSaveDelegates.Add(newDelegate);
        }
예제 #44
0
        private void SaveAndCompareTexture(Image outputImage, string fileName, ImageFileType extension = ImageFileType.Png)
        {
            // save
            Directory.CreateDirectory(ImageOutputPath);
            outputImage.Save(new FileStream(ImageOutputPath + fileName + extension.ToFileExtension(), FileMode.Create), extension); 

            // Compare
            using(var texTool = new TextureTool())
            {
                var referenceImage = LoadImage(texTool, new UFile(GoldImagePath + "/" + fileName + extension.ToFileExtension()));
                Assert.IsTrue(CompareImages(outputImage, referenceImage), "The texture outputted differs from the gold image.");
            }
        }
예제 #45
0
파일: Image.cs 프로젝트: Julyuary/paradox
        /// <summary>
        /// Saves this instance to a stream.
        /// </summary>
        /// <param name="pixelBuffers">The buffers to save.</param>
        /// <param name="count">The number of buffers to save.</param>
        /// <param name="description">Global description of the buffer.</param>
        /// <param name="imageStream">The destination stream.</param>
        /// <param name="fileType">Specify the output format.</param>
        /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks>
        internal static void Save(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFileType fileType)
        {
            foreach (var loadSaveDelegate in loadSaveDelegates)
            {
                if (loadSaveDelegate.FileType == fileType)
                {
                    loadSaveDelegate.Save(pixelBuffers, count, description, imageStream);
                    return;
                }

            }
            throw new NotSupportedException("This file format is not yet implemented.");
        }
 private void OnEnable()
 {
     path     = EditorPrefs.GetString(EditorCommon.GetProjectRelatedEditorPrefsKey(EDITOR_PREF_PATH_KEYS), "Assets/");
     size     = EditorPrefs.GetInt(EditorCommon.GetProjectRelatedEditorPrefsKey(EDITOR_PREF_SIZE_KEYS), 512);
     fileType = (ImageFileType)EditorPrefs.GetInt(EditorCommon.GetProjectRelatedEditorPrefsKey(EDITOR_PREF_FILE_TYPE_KEYS), 0);
 }