示例#1
0
 public void Save(Document input, Stream output, SaveConfigToken token, ProgressEventHandler callback, bool rememberToken)
 {
     using (Surface scratch = new Surface(input.Width, input.Height))
     {
         Save(input, output, token, callback, rememberToken);
     }
 }
示例#2
0
        public void SignIn(string Email, string Password, string Imap = "", int iport = 0)
        {
            UserManagement userManagement = new UserManagement(Email: Email, Password: Password);
            int            userId         = userManagement.GetUser().U_Id;

            try
            {
                Random r = new Random();
                MailKitClient = new SmtpClient(new ProtocolLogger("smtp" + r.Next(1, 100).ToString() + ".log"));
                ProgressEventHandler pg = Progress;
                pg?.Invoke("Validating server");
                pg?.Invoke("Authenticating server");
                MailKitClient.Connect(Imap, iport, SecureSocketOptions.StartTlsWhenAvailable);
                pg?.Invoke("Signing in");
                MailKitClient.Authenticate(Email, Password);
            }
            catch (Exception ex)
            {
                errorstring = "Failed to authenticate user " + Environment.NewLine + "Details : " + ex.ToString();
                ExceptionEventHandler error = ErrorOccured;
                error?.Invoke(ex.ToString());
            }
            if (errorstring == "")
            {
                AuthSuccessEventHandler Success = AuthSuccess;
                Success?.Invoke(userId);
            }
        }
示例#3
0
        public void Save(Document input, Stream output, SaveConfig token, Surface scratchSurface,
                         ProgressEventHandler callback, bool rememberToken)
        {
            if (!this.SupportsSaving)
            {
                throw new NotImplementedException("Saving is not supported by this FileType");
            }
            else
            {
                Surface disposeMe = null;

                if (scratchSurface == null)
                {
                    disposeMe      = new Surface(input.Size);
                    scratchSurface = disposeMe;
                }
                else if (scratchSurface.Size != input.Size)
                {
                    throw new ArgumentException("scratchSurface.Size must equal input.Size");
                }

                OnSave(input, output, token, scratchSurface, callback);

                if (disposeMe != null)
                {
                    disposeMe.Dispose();
                }
            }
        }
示例#4
0
        public static void Save(
            Document input,
            Stream output,
            DdsFileFormat format,
            DdsErrorMetric errorMetric,
            BC7CompressionMode compressionMode,
            bool cubeMap,
            bool generateMipmaps,
            MipMapSampling sampling,
            Surface scratchSurface,
            ProgressEventHandler progressCallback)
        {
            using (RenderArgs args = new RenderArgs(scratchSurface))
            {
                input.Render(args, true);
            }

            DdsProgressCallback ddsProgress = null;

            if (progressCallback != null)
            {
                ddsProgress = (UIntPtr done, UIntPtr total) =>
                {
                    double progress = (double)done.ToUInt64() / (double)total.ToUInt64();
                    progressCallback(null, new ProgressEventArgs(progress * 100.0, true));
                };
            }

            SaveDdsFile(scratchSurface, format, errorMetric, compressionMode, cubeMap, generateMipmaps, sampling, output, ddsProgress);
        }
示例#5
0
 protected ProjectBuilder(Project project, ProgressEventHandler total_handler, ProgressEventHandler task_handler)
 {
     this.project = project;
     this.total_handler = total_handler;
     this.task_handler = task_handler;
     total = new ProgressEventArgs ();
 }
示例#6
0
 public void CreateTables(ProgressEventHandler progress, string userName, string password)
 {
     using (IDbConnection Db = this.appHost.TryResolve <IDbConnectionFactory>().OpenDbConnection())
     {
         GuruxAMI.Service.GXManagementService.InitializeDB(Db, progress, userName, password);
     }
 }
        protected override HistoryMemento OnTransactedToolUndo(TTool tool, ProgressEventHandler progressCallback)
        {
            tool.VerifyState(TransactedToolState.Dirty);
            TChanges changes = tool.Changes;

            return(new TransactedToolUndoCommitHistoryMemento <TTool, TChanges>(base.DocumentWorkspace, changes, tool.CommitChangesInner(changes)));
        }
示例#8
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            ReplaceDocumentHistoryMemento memento = new ReplaceDocumentHistoryMemento(base.Name, base.Image, this.historyWorkspace);

            this.historyWorkspace.Document = ((ReplaceDocumentHistoryMementoData)base.Data).OldDocument;
            return(memento);
        }
示例#9
0
        internal override void FinalSave(
            Document input,
            Stream output,
            Surface scratchSurface,
            int ditherLevel,
            SavableBitDepths bitDepth,
            PropertyBasedSaveConfigToken token,
            ProgressEventHandler progressCallback)
        {
            bool enableAlpha;

            switch (bitDepth)
            {
            case SavableBitDepths.Rgb8:
                enableAlpha = false;
                break;

            case SavableBitDepths.Rgba8:
                enableAlpha = true;
                break;

            default:
                throw new InvalidEnumArgumentException("bitDepth", (int)bitDepth, typeof(SavableBitDepths));
            }

            using (Bitmap quantized = Quantize(scratchSurface, ditherLevel, 256, enableAlpha, progressCallback))
            {
                quantized.Save(output, ImageFormat.Gif);
            }
        }
        private HistoryMemento ImportOneFile(DocumentWorkspace documentWorkspace, string fileName, out Rectangle lastLayerBounds)
        {
            documentWorkspace.AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();

            ProgressEventHandler progressCallback =
                delegate(object sender, ProgressEventArgs e)
            {
                documentWorkspace.AppWorkspace.Widgets.StatusBarProgress.SetProgressStatusBar(e.Percent);
            };

            FileType fileType;
            Document document = DocumentWorkspace.LoadDocument(documentWorkspace, fileName, out fileType, progressCallback);

            documentWorkspace.AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBar();

            if (document != null)
            {
                string name = Path.ChangeExtension(Path.GetFileName(fileName), null);
                string newLayerNameFormat = PdnResources.GetString("ImportFromFileAction.ImportOneFile.NewLayer.Format");

                foreach (Layer layer in document.Layers)
                {
                    layer.Name         = string.Format(newLayerNameFormat, name, layer.Name);
                    layer.IsBackground = false;
                }

                HistoryMemento ha = ImportDocument(documentWorkspace, document, out lastLayerBounds);
                return(ha);
            }
            else
            {
                lastLayerBounds = Rectangle.Empty;
                return(null);
            }
        }
示例#11
0
 public AvifWriter(IReadOnlyList <CompressedAV1Image> colorImages,
                   IReadOnlyList <CompressedAV1Image> alphaImages,
                   AvifMetadata metadata,
                   ImageGridMetadata imageGridMetadata,
                   YUVChromaSubsampling chromaSubsampling,
                   ColorInformationBox colorInformationBox,
                   ProgressEventHandler progressEventHandler,
                   uint progressDone,
                   uint progressTotal,
                   IByteArrayPool arrayPool)
 {
     this.state                 = new AvifWriterState(colorImages, alphaImages, imageGridMetadata, metadata, arrayPool);
     this.arrayPool             = arrayPool;
     this.colorImageIsGrayscale = chromaSubsampling == YUVChromaSubsampling.Subsampling400;
     this.colorInformationBox   = colorInformationBox;
     this.progressCallback      = progressEventHandler;
     this.progressDone          = progressDone;
     this.progressTotal         = progressTotal;
     this.fileTypeBox           = new FileTypeBox(chromaSubsampling);
     this.metaBox               = new MetaBox(this.state.PrimaryItemId,
                                              this.state.Items.Count,
                                              this.state.MediaDataBoxContentSize > uint.MaxValue,
                                              this.state.ItemDataBox);
     PopulateMetaBox();
 }
示例#12
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            BitmapHistoryMementoData data = base.Data as BitmapHistoryMementoData;
            BitmapLayer layer             = (BitmapLayer)this.historyWorkspace.Document.Layers[this.layerIndex];

            RectInt32[]          savedRegion = data.SavedRegion;
            MaskedSurface        surface     = null;
            BitmapHistoryMemento memento     = new BitmapHistoryMemento(base.Name, base.Image, this.historyWorkspace, this.layerIndex, savedRegion);

            if (surface != null)
            {
                surface.Draw(layer.Surface);
            }
            else
            {
                using (FileStream stream = FileSystem.OpenStreamingFile(this.tempFileName, FileAccess.Read))
                {
                    LoadSurfaceRegion(stream, layer.Surface, data.SavedRegion);
                }
                this.tempFileHandle.Dispose();
                this.tempFileHandle = null;
            }
            if (savedRegion.Length != 0)
            {
                RectInt32 roi = savedRegion.Bounds();
                layer.Invalidate(roi);
            }
            return(memento);
        }
示例#13
0
        private unsafe void FinalSave(Document input, Stream output, Surface scratchSurface, int ditherLevel, int threshold, SavableBitDepths bitDepth, PropertyBasedSaveConfigToken token, ProgressEventHandler progressCallback, double progressStart, double progressEnd)
        {
            this.RenderFlattenedDocument(input, scratchSurface);
            if (((bitDepth == SavableBitDepths.Rgb8) || (bitDepth == SavableBitDepths.Rgba8)) || (bitDepth == SavableBitDepths.Rgb24))
            {
                ColorBgra white = ColorBgra.White;
                Work.ParallelFor(WaitType.Blocking, 0, scratchSurface.Height, delegate(int y) {
                    int width             = scratchSurface.Width;
                    ColorBgra *rowAddress = scratchSurface.GetRowAddress(y);
                    for (int j = 0; j < width; j++)
                    {
                        ColorBgra rhs = rowAddress[0];
                        if ((bitDepth == SavableBitDepths.Rgba8) && (rhs.A < threshold))
                        {
                            rowAddress->Bgra = 0;
                        }
                        else
                        {
                            rowAddress->Bgra = CompositionOps.Normal.ApplyStatic(white, rhs).Bgra;
                        }
                        rowAddress++;
                    }
                }, WorkItemQueuePriority.Normal, null);
            }
            ProgressEventHandler handler = (sender, e) => progressCallback(sender, new ProgressEventArgs(progressStart + ((progressEnd - progressStart) * (e.Percent / 100.0))));

            this.OnFinalSave(input, output, scratchSurface, ditherLevel, bitDepth, token, handler);
        }
示例#14
0
文件: PsExporter.cs 项目: 15831944/WW
 public void Draw(
     DxfModel model,
     GraphicsConfig config,
     Matrix4D modelToPsTransform,
     ProgressEventHandler progressEventHandler)
 {
     this.Write(model, (DxfLayout)null, (ICollection <DxfViewport>)null, config, modelToPsTransform, progressEventHandler);
 }
示例#15
0
 internal abstract void FinalSave(
     Document input,
     Stream output,
     Surface scratchSurface,
     int ditherLevel,
     SavableBitDepths bitDepth,
     PropertyBasedSaveConfigToken token,
     ProgressEventHandler progressCallback);
示例#16
0
 public ProgressChecker()
 {
     progressEventHandler = new ProgressEventHandler(update =>
     {
         lastProgress     = update.GetProgress();
         areTasksFinished = update.GetUnfinishedLeafTasks().Length == 0;
     });
 }
示例#17
0
        protected override void OnSave(Document input, Stream output, SaveConfigToken token, 
            Surface scratchSurface, ProgressEventHandler callback)
        {
            RenderArgs ra = new RenderArgs(new Surface(input.Size));
            input.Render(ra);

            ra.Bitmap.Save(output, ImageFormat.Bmp);
        }
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            MoveLayerHistoryMemento memento = new MoveLayerHistoryMemento(base.Name, base.Image, this.historyWorkspace, this.newIndex, this.oldIndex);

            this.historyWorkspace.Document.Layers.Move(this.newIndex, this.oldIndex);
            this.historyWorkspace.Document.Invalidate();
            return(memento);
        }
示例#19
0
 /// <summary>
 /// Detects any edges within the image. Uses the <see cref="SobelProcessor{T,TP}"/> filter
 /// operating in Grayscale mode.
 /// </summary>
 /// <typeparam name="T">The pixel format.</typeparam>
 /// <typeparam name="TP">The packed format. <example>long, float.</example></typeparam>
 /// <param name="source">The image this method extends.</param>
 /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
 /// <returns>The <see cref="Image{T,TP}"/>.</returns>
 public static Image <T, TP> DetectEdges <T, TP>(this Image <T, TP> source, ProgressEventHandler progressHandler = null)
     where T : IPackedVector <TP>
     where TP : struct
 {
     return(DetectEdges(source, source.Bounds, new SobelProcessor <T, TP> {
         Grayscale = true
     }, progressHandler));
 }
示例#20
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            MetadataHistoryMemento     memento = new MetadataHistoryMemento(base.Name, base.Image, this.historyWorkspace);
            MetadataHistoryMementoData data    = (MetadataHistoryMementoData)base.Data;

            this.historyWorkspace.Document.ReplaceMetadataFrom(data.Document);
            return(memento);
        }
示例#21
0
 internal static void CreateTable <T>(IDbConnection Db, ref int index, ProgressEventHandler progress) where T : new()
 {
     Db.CreateTable <T>(false);
     if (progress != null)
     {
         progress(++index, 45);
     }
 }
        protected override HistoryMemento OnTransactedToolUndo(TTool tool, ProgressEventHandler progressCallback)
        {
            tool.VerifyState(TransactedToolState.Idle);
            HistoryMemento memento = this.innerCommitHM.PerformUndo(progressCallback);

            tool.RestoreChanges(this.changes);
            return(new TransactedToolRedoCommitHistoryMemento <TTool, TChanges>(base.DocumentWorkspace, base.Name, base.Image));
        }
示例#23
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            SelectionHistoryMemento     memento = new SelectionHistoryMemento(base.Name, base.Image, this.historyWorkspace);
            SelectionHistoryMementoData data    = (SelectionHistoryMementoData)base.Data;
            SelectionData savedSelectionData    = data.SavedSelectionData;

            this.historyWorkspace.Selection.Restore(savedSelectionData);
            return(memento);
        }
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            HistoryMemento memento = new LayerPropertyHistoryMemento(base.Name, base.Image, this.historyWorkspace, this.layerIndex);
            Layer          layer   = (Layer)this.historyWorkspace.Document.Layers[this.layerIndex];

            layer.LoadProperties(this.properties, true);
            layer.PerformPropertyChanged();
            return(memento);
        }
示例#25
0
        public HistoryMemento PerformUndo(ProgressEventHandler progressCallback = null)
        {
            ProgressEventHandler handler = progressCallback ?? (< > c.< > 9__25_0 ?? (< > c.< > 9__25_0 = new ProgressEventHandler(< > c.< > 9. < PerformUndo > b__25_0)));
            HistoryMemento       memento = this.OnUndo(handler);

            memento.ID         = this.ID;
            memento.SeriesGuid = this.SeriesGuid;
            return(memento);
        }
示例#26
0
 protected sealed override void OnSaveT(Document input, Stream output, PropertyBasedSaveConfigToken token, Surface scratchSurface, ProgressEventHandler progressCallback)
 {
     try
     {
         int  num3;
         bool flag;
         bool flag2;
         int  num4;
         int  thresholdFromToken   = this.GetThresholdFromToken(token);
         int  ditherLevelFromToken = this.GetDitherLevelFromToken(token);
         HashSet <SavableBitDepths> allowedBitDepths = this.CreateAllowedBitDepthListFromToken(token);
         if (allowedBitDepths.Count == 0)
         {
             throw new ArgumentException("there must be at least 1 element returned from CreateAllowedBitDepthListFromToken()");
         }
         SavableBitDepths[] items = new SavableBitDepths[] { SavableBitDepths.Rgb8, SavableBitDepths.Rgba8 };
         if (allowedBitDepths.IsSubsetOf(HashSetUtil.Create <SavableBitDepths>(items)))
         {
             num3 = thresholdFromToken;
         }
         else
         {
             num3 = 1;
         }
         this.RenderFlattenedDocument(input, scratchSurface);
         this.Analyze(scratchSurface, out flag, out flag2, out num4);
         HashSet <SavableBitDepths> losslessBitDepths = new HashSet <SavableBitDepths> {
             SavableBitDepths.Rgba32
         };
         if (flag)
         {
             losslessBitDepths.Add(SavableBitDepths.Rgb24);
             if (num4 <= 0x100)
             {
                 losslessBitDepths.Add(SavableBitDepths.Rgb8);
             }
         }
         else if (flag2 && (num4 < 0x100))
         {
             losslessBitDepths.Add(SavableBitDepths.Rgba8);
         }
         double chooseBitDepthProgressLast = 0.0;
         ProgressEventHandler handler      = delegate(object sender, ProgressEventArgs e) {
             chooseBitDepthProgressLast = e.Percent;
             progressCallback(sender, e);
         };
         SavableBitDepths bitDepth = this.ChooseBitDepth(input, scratchSurface, ditherLevelFromToken, num3, token, handler, 0.0, 66.666666666666671, allowedBitDepths, losslessBitDepths, flag, flag2, num4);
         if (((bitDepth == SavableBitDepths.Rgba8) && (num3 == 0)) && (allowedBitDepths.Contains(SavableBitDepths.Rgba8) && allowedBitDepths.Contains(SavableBitDepths.Rgb8)))
         {
             bitDepth = SavableBitDepths.Rgb8;
         }
         this.FinalSave(input, output, scratchSurface, ditherLevelFromToken, num3, bitDepth, token, progressCallback, chooseBitDepthProgressLast, 100.0);
     }
     finally
     {
     }
 }
示例#27
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            FlipLayerHistoryMemento memento = new FlipLayerHistoryMemento(base.Name, base.Image, this.historyWorkspace, this.layerIndex, this.flipType);
            BitmapLayer             layer   = (BitmapLayer)this.historyWorkspace.Document.Layers[this.layerIndex];

            FlipInPlace(layer.Surface, this.flipType);
            layer.Invalidate();
            return(memento);
        }
示例#28
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            DeleteLayerHistoryMementoData data = (DeleteLayerHistoryMementoData)base.Data;
            HistoryMemento memento             = new NewLayerHistoryMemento(base.Name, base.Image, this.historyWorkspace, this.index);

            this.historyWorkspace.Document.Layers.Insert(this.index, data.Layer);
            ((Layer)this.historyWorkspace.Document.Layers[this.index]).Invalidate();
            return(memento);
        }
示例#29
0
        protected virtual void OnTableLoadProgressChanged(ProgressEventArgs args)
        {
            ProgressEventHandler handler = TableLoadProgressChanged;

            if (handler != null)
            {
                handler(this, args);
            }
        }
示例#30
0
        /// <summary>
        /// 触发进度事件
        /// </summary>
        /// <param name="e">数据</param>
        protected virtual void OnProgress(ProgressEventArgs e)
        {
            ProgressEventHandler handler = this.Events[EVENT_PROGRESS] as ProgressEventHandler;

            if (handler != null)
            {
                handler(this, e);
            }
        }
示例#31
0
        protected override HistoryMemento OnUndo(ProgressEventHandler progressCallback)
        {
            SelectionInterimTransformHistoryMemento memento = new SelectionInterimTransformHistoryMemento(base.Name, base.Image, this.historyWorkspace);

            using (this.historyWorkspace.Selection.UseChangeScope())
            {
                this.historyWorkspace.Selection.SetInterimTransform(this.interimTx);
            }
            return(memento);
        }
示例#32
0
        protected virtual void OnProgressChanged(ProgressEventArgs e)
        {
            _currentProgress = e.Progress;
            ProgressEventHandler handler = ProgressChanged;

            if (handler != null)
            {
                handler(this, e);
            }
        }
示例#33
0
 protected override void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
 {
     if (callback == null)
     {
         input.SaveToStream(output);
     }
     else
     {
         UpdateProgressTranslator upt = new UpdateProgressTranslator(ApproximateMaxOutputOffset(input), callback);
         input.SaveToStream(output, new IOEventHandler(upt.IOEventHandler));
     }
 }
示例#34
0
        protected override void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler progressCallback)
        {
            GifSaveConfigToken gsct = (GifSaveConfigToken)token;

            // Flatten and pre-process the image
            scratchSurface.Clear(ColorBgra.FromBgra(255, 255, 255, 0));

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, true);
            }

            for (int y = 0; y < scratchSurface.Height; ++y)
            {
                unsafe
                {
                    ColorBgra* ptr = scratchSurface.GetRowAddressUnchecked(y);

                    for (int x = 0; x < scratchSurface.Width; ++x)
                    {
                        if (ptr->A < gsct.Threshold)
                        {
                            ptr->Bgra = 0;
                        }
                        else
                        {
                            if (gsct.PreMultiplyAlpha)
                            {
                                int r = ((ptr->R * ptr->A) + (255 * (255 - ptr->A))) / 255;
                                int g = ((ptr->G * ptr->A) + (255 * (255 - ptr->A))) / 255;
                                int b = ((ptr->B * ptr->A) + (255 * (255 - ptr->A))) / 255;
                                int a = 255;

                                *ptr = ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a);
                            }
                            else
                            {
                                ptr->Bgra |= 0xff000000;
                            }
                        }

                        ++ptr;
                    }
                }
            }

            using (Bitmap quantized = Quantize(scratchSurface, gsct.DitherLevel, 255, progressCallback))
            {
                quantized.Save(output, ImageFormat.Gif);
            }
        }
        /// <summary>
        /// Combines the given image together with the current one by blending their pixels.
        /// </summary>
        /// <param name="source">The image this method extends.</param>
        /// <param name="color">The color to set as the background.</param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/>.</returns>
        public static Image BackgroundColor(this Image source, Color color, ProgressEventHandler progressHandler = null)
        {
            BackgroundColor processor = new BackgroundColor(color);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(source.Bounds, processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
        /// <summary>
        /// Alters the alpha component of the image.
        /// </summary>
        /// <param name="source">The image this method extends.</param>
        /// <param name="percent">The new opacity of the image. Must be between 0 and 100.</param>
        /// <param name="rectangle">
        /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to alter.
        /// </param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/>.</returns>
        public static Image Alpha(this Image source, int percent, Rectangle rectangle, ProgressEventHandler progressHandler = null)
        {
            Alpha processor = new Alpha(percent);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(rectangle, processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
        /// <summary>
        /// Crops an image to the area of greatest entropy.
        /// </summary>
        /// <param name="source">The image to crop.</param>
        /// <param name="threshold">The threshold for entropic density.</param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        public static Image EntropyCrop(this Image source, float threshold = .5f, ProgressEventHandler progressHandler = null)
        {
            EntropyCrop processor = new EntropyCrop(threshold);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(source.Width, source.Height, source.Bounds, source.Bounds, processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
示例#38
0
        public static void Save(Document input, Stream output, Surface scratchSurface, ImageFormat format, ProgressEventHandler callback)
        {
            // flatten the document
            scratchSurface.Clear(ColorBgra.FromBgra(0, 0, 0, 0));

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, true);
            }

            using (Bitmap bitmap = scratchSurface.CreateAliasedBitmap())
            {
                LoadProperties(bitmap, input);
                bitmap.Save(output, format);
            }
        }
示例#39
0
        protected override unsafe void OnSave( Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback )
		{
			DdsSaveConfigToken ddsToken = ( DdsSaveConfigToken )token;

			// We need to be able to feast on the goo inside..
			scratchSurface.Clear( ColorBgra.Transparent );

			using ( RenderArgs ra = new RenderArgs( scratchSurface ) )
			{
				input.Render( ra, true );
			}

			// Create the DDS file, and save it..
			DdsFile ddsFile = new DdsFile();
			ddsFile.Save( output, scratchSurface, ddsToken, callback );
		}
        /// <summary>
        /// Crops an image to the given width and height with the given source rectangle.
        /// <remarks>
        /// If the source rectangle is smaller than the target dimensions then the
        /// area within the source is resized performing a zoomed crop.
        /// </remarks>
        /// </summary>
        /// <param name="source">The image to crop.</param>
        /// <param name="width">The target image width.</param>
        /// <param name="height">The target image height.</param>
        /// <param name="sourceRectangle">
        /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to draw.
        /// </param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        public static Image Crop(this Image source, int width, int height, Rectangle sourceRectangle, ProgressEventHandler progressHandler = null)
        {
            if (sourceRectangle.Width < width || sourceRectangle.Height < height)
            {
                // If the source rectangle is smaller than the target perform a
                // cropped zoom.
                source = source.Resize(sourceRectangle.Width, sourceRectangle.Height);
            }

            Crop processor = new Crop();
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(width, height, sourceRectangle, new Rectangle(0, 0, width, height), processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
示例#41
0
        protected override void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
        {
            JpegSaveConfigToken jsct = (JpegSaveConfigToken)token;

            ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
            EncoderParameters parms = new EncoderParameters(1);
            EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, jsct.Quality); // force '95% quality'
            parms.Param[0] = parm;

            scratchSurface.Clear(ColorBgra.White);

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, true);
            }

            using (Bitmap bitmap = scratchSurface.CreateAliasedBitmap())
            {
                GdiPlusFileType.LoadProperties(bitmap, input);
                bitmap.Save(output, icf, parms);
            }
        }
示例#42
0
        protected override void OnSaveT(Document input, Stream output, PropertyBasedSaveConfigToken token, Surface scratchSurface, ProgressEventHandler progressCallback)
        {
            int quality = token.GetProperty<Int32Property>(PropertyNames.Quality).Value;

            ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
            EncoderParameters parms = new EncoderParameters(1);
            EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            parms.Param[0] = parm;

            scratchSurface.Clear(ColorBgra.White);

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, false);
            }

            using (Bitmap bitmap = scratchSurface.CreateAliasedBitmap())
            {
                GdiPlusFileType.LoadProperties(bitmap, input);
                bitmap.Save(output, icf, parms);
            }
        }
示例#43
0
        protected override void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
        {
            ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
            EncoderParameters parms = new EncoderParameters(1);
            EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24); // BMP's should always save as 24-bit
            parms.Param[0] = parm;

            scratchSurface.Clear(ColorBgra.White);

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, true);
            }

            // In order to save memory, we 'squish' the 32-bit bitmap down to 24-bit in-place
            // instead of allocating a new bitmap and copying it over.
            SquishSurfaceTo24Bpp(scratchSurface);

            using (Bitmap bitmap = CreateAliased24BppBitmap(scratchSurface))
            {
                GdiPlusFileType.LoadProperties(bitmap, input);
                bitmap.Save(output, icf, parms);
            }
        }
        /// <summary>
        /// Resizes an image to the given width and height with the given sampler and
        /// source rectangle.
        /// </summary>
        /// <param name="source">The image to resize.</param>
        /// <param name="width">The target image width.</param>
        /// <param name="height">The target image height.</param>
        /// <param name="sampler">The <see cref="IResampler"/> to perform the resampling.</param>
        /// <param name="sourceRectangle">
        /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to draw.
        /// </param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        /// <remarks>Passing zero for one of height or width will automatically preserve the aspect ratio of the original image</remarks>
        public static Image Resize(this Image source, int width, int height, IResampler sampler, Rectangle sourceRectangle, ProgressEventHandler progressHandler = null)
        {
            if (width == 0 && height > 0)
            {
                width = source.Width * height / source.Height;
            }

            if (height == 0 && width > 0)
            {
                height = source.Height * width / source.Width;
            }

            Resize processor = new Resize(sampler);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(width, height, sourceRectangle, new Rectangle(0, 0, width, height), processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
 /// <summary>
 /// Resizes an image to the given width and height with the given sampler.
 /// </summary>
 /// <param name="source">The image to resize.</param>
 /// <param name="width">The target image width.</param>
 /// <param name="height">The target image height.</param>
 /// <param name="sampler">The <see cref="IResampler"/> to perform the resampling.</param>
 /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
 /// <returns>The <see cref="Image"/></returns>
 /// <remarks>Passing zero for one of height or width will automatically preserve the aspect ratio of the original image</remarks>
 public static Image Resize(this Image source, int width, int height, IResampler sampler, ProgressEventHandler progressHandler = null)
 {
     return Resize(source, width, height, sampler, source.Bounds, progressHandler);
 }
示例#46
0
        /// <summary>
        /// Takes a Surface and quantizes it down to an 8-bit bitmap.
        /// </summary>
        /// <param name="quantizeMe">The Surface to quantize.</param>
        /// <param name="ditherAmount">How strong should dithering be applied. 0 for no dithering, 8 for full dithering.</param>
        /// <param name="maxColors">The maximum number of colors to use. This may range from 2 to 255.</param>
        /// <param name="progressCallback">The progress callback delegate.</param>
        /// <returns>An 8-bit Bitmap that is the same size as quantizeMe.</returns>
        protected Bitmap Quantize(Surface quantizeMe, int ditherAmount, int maxColors, ProgressEventHandler progressCallback)
        {
            if (ditherAmount < 0 || ditherAmount > 8)
            {
                throw new ArgumentOutOfRangeException(
                    "ditherAmount",
                    ditherAmount,
                    "Out of bounds. Must be in the range [0, 8]");
            }

            if (maxColors < 2 || maxColors > 255)
            {
                throw new ArgumentOutOfRangeException(
                    "maxColors",
                    maxColors,
                    "Out of bounds. Must be in the range [2, 255]");
            }

            using (Bitmap bitmap = quantizeMe.CreateAliasedBitmap(quantizeMe.Bounds, true))
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(maxColors, 8);
                quantizer.DitherLevel = ditherAmount;
                Bitmap quantized = quantizer.Quantize(bitmap, progressCallback);
                return quantized;
            }
        }
示例#47
0
        /// <summary>
        /// Because the old OnSave() method is obsolete, we must use reflection to call it.
        /// This is important for legacy FileType plugins. It allows us to ensure that no
        /// new plugins can be compiled using the old OnSave() overload.
        /// </summary>
        private void OldOnSaveTrampoline(Document input, Stream output, SaveConfigToken token, ProgressEventHandler callback)
        {
            MethodInfo onSave = GetType().GetMethod(
                "OnSave",
                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy,
                Type.DefaultBinder,
                new Type[]
                {
                    typeof(Document),
                    typeof(Stream),
                    typeof(SaveConfigToken),
                    typeof(ProgressEventHandler)
                },
                null);

            onSave.Invoke(
                this,
                new object[]
                {
                    input,
                    output,
                    token,
                    callback
                });
        }
示例#48
0
 protected virtual void OnSave(Document input, Stream output, SaveConfigToken token, ProgressEventHandler callback)
 {
 }
示例#49
0
 protected virtual void OnSave(Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
 {
     throw new OnSaveNotImplementedException("Derived classes must implement this method. It is virtual instead of abstract in order to maintain compatibility with legacy plugins.");
 }
示例#50
0
 public void Save(Document input, Stream output, SaveConfigToken token, ProgressEventHandler callback, bool rememberToken)
 {
     using (Surface scratch = new Surface(input.Width, input.Height))
     {
         Save(input, output, token, callback, rememberToken);
     }
 }
示例#51
0
        internal override void FinalSave(
            Document input, 
            Stream output, 
            Surface scratchSurface, 
            int ditherLevel, 
            SavableBitDepths bitDepth,
            PropertyBasedSaveConfigToken token,
            ProgressEventHandler progressCallback)
        {
            // finally, do the save.
            if (bitDepth == SavableBitDepths.Rgb24)
            {
                // In order to save memory, we 'squish' the 32-bit bitmap down to 24-bit in-place
                // instead of allocating a new bitmap and copying it over.
                SquishSurfaceTo24Bpp(scratchSurface);

                ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
                EncoderParameters parms = new EncoderParameters(1);
                EncoderParameter parm = new EncoderParameter(Encoder.ColorDepth, 24);
                parms.Param[0] = parm;

                using (Bitmap bitmap = CreateAliased24BppBitmap(scratchSurface))
                {
                    GdiPlusFileType.LoadProperties(bitmap, input);
                    bitmap.Save(output, icf, parms);
                }
            }
            else if (bitDepth == SavableBitDepths.Rgb8)
            {
                using (Bitmap quantized = Quantize(scratchSurface, ditherLevel, 256, false, progressCallback))
                {
                    ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
                    EncoderParameters parms = new EncoderParameters(1);
                    EncoderParameter parm = new EncoderParameter(Encoder.ColorDepth, 8);
                    parms.Param[0] = parm;

                    GdiPlusFileType.LoadProperties(quantized, input);
                    quantized.Save(output, icf, parms);
                }
            }
            else
            {
                throw new InvalidEnumArgumentException("bitDepth", (int)bitDepth, typeof(SavableBitDepths));
            }
        }
        /// <summary>
        /// Rotates an image by the given angle in degrees.
        /// </summary>
        /// <param name="source">The image to resize.</param>
        /// <param name="degrees">The angle in degrees to perform the rotation.</param>
        /// <param name="sampler">The <see cref="IResampler"/> to perform the resampling.</param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        public static Image Rotate(this Image source, float degrees, IResampler sampler, ProgressEventHandler progressHandler = null)
        {
            Rotate processor = new Rotate(sampler) { Angle = degrees };
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(source.Width, source.Height, source.Bounds, source.Bounds, processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
示例#53
0
 public UpdateProgressTranslator(long maxBytes, ProgressEventHandler callback)
 {
     this.maxBytes = maxBytes;
     this.callback = callback;
     this.totalBytes = 0;
 }
        /// <summary>
        /// Rotates and flips an image by the given instructions.
        /// </summary>
        /// <param name="source">The image to resize.</param>
        /// <param name="rotateType">The <see cref="RotateType"/> to perform the rotation.</param>
        /// <param name="flipType">The <see cref="FlipType"/> to perform the flip.</param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        public static Image RotateFlip(this Image source, RotateType rotateType, FlipType flipType, ProgressEventHandler progressHandler = null)
        {
            RotateFlip processor = new RotateFlip(rotateType, flipType);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(source.Width, source.Height, source.Bounds, source.Bounds, processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
 /// <summary>
 /// Crops an image to the given width and height.
 /// </summary>
 /// <param name="source">The image to resize.</param>
 /// <param name="width">The target image width.</param>
 /// <param name="height">The target image height.</param>
 /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
 /// <returns>The <see cref="Image"/></returns>
 public static Image Crop(this Image source, int width, int height, ProgressEventHandler progressHandler = null)
 {
     return Crop(source, width, height, source.Bounds, progressHandler);
 }
 /// <summary>
 /// Resizes an image to the given width and height.
 /// </summary>
 /// <param name="source">The image to resize.</param>
 /// <param name="width">The target image width.</param>
 /// <param name="height">The target image height.</param>
 /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
 /// <returns>The <see cref="Image"/></returns>
 /// <remarks>Passing zero for one of height or width will automatically preserve the aspect ratio of the original image</remarks>
 public static Image Resize(this Image source, int width, int height, ProgressEventHandler progressHandler = null)
 {
     return Resize(source, width, height, new BicubicResampler(), progressHandler);
 }
示例#57
0
        private void SaveTga(Surface input, Stream output, SavableBitDepths bitDepth, bool rleCompress, ProgressEventHandler progressCallback)
        {
            TgaHeader header = new TgaHeader();

            header.idLength = 0;
            header.cmapType = 0;
            header.imageType = rleCompress ? TgaType.RleRgb : TgaType.Rgb;
            header.cmapIndex = 0;
            header.cmapLength = 0;
            header.cmapEntrySize = 0; // if bpp=8, set this to 24
            header.xOrigin = 0;
            header.yOrigin = 0;
            header.imageWidth = (ushort)input.Width;
            header.imageHeight = (ushort)input.Height;

            header.imageDesc = 0;

            switch (bitDepth)
            {
                case SavableBitDepths.Rgba32:
                    header.pixelDepth = 32;
                    header.imageDesc |= 8;
                    break;

                case SavableBitDepths.Rgb24:
                    header.pixelDepth = 24;
                    break;

                default:
                    throw new InvalidEnumArgumentException("bitDepth", (int)bitDepth, typeof(SavableBitDepths));
            }

            header.Write(output);

            // write palette if doing 8-bit
            // ... todo?

            for (int y = input.Height - 1; y >= 0; --y)
            {
                // non-rle output
                if (rleCompress)
                {
                    SaveTgaRowRle(output, input, ref header, y);
                }
                else
                {
                    SaveTgaRowRaw(output, input, ref header, y);
                }

                if (progressCallback != null)
                {
                    progressCallback(this, new ProgressEventArgs(100.0 * ((double)(input.Height - y) / (double)input.Height)));
                }
            }
        }
示例#58
0
        public void Save(
            Document input,
            Stream output,
            SaveConfigToken token,
            Surface scratchSurface,
            ProgressEventHandler callback,
            bool rememberToken)
        {
            if (!this.SupportsSaving)
            {
                throw new NotImplementedException("Saving is not supported by this FileType");
            }
            else
            {
                Surface disposeMe = null;

                if (scratchSurface == null)
                {
                    disposeMe = new Surface(input.Size);
                    scratchSurface = disposeMe;
                }
                else if (scratchSurface.Size != input.Size)
                {
                    throw new ArgumentException("scratchSurface.Size must equal input.Size");
                }

                if (rememberToken)
                {
                    Type ourType = this.GetType();
                    string savedTokenName = ourType.Namespace + "." + ourType.Name;
                    SoapFormatter soap = new SoapFormatter();
                    MemoryStream ms = new MemoryStream();
                    soap.Serialize(ms, token);
                    byte[] bytes = ms.GetBuffer();
                    string utf8 = Encoding.UTF8.GetString(bytes);
                    Settings.CurrentUser.SetString(savedTokenName, utf8);
                }

                if (!this.SavesWithProgress)
                {
                    try
                    {
                        OnSave(input, output, token, scratchSurface, null);
                    }

                    catch (OnSaveNotImplementedException)
                    {
                        OldOnSaveTrampoline(input, output, token, null);
                    }
                }
                else
                {
                    try
                    {
                        OnSave(input, output, token, scratchSurface, callback);
                    }

                    catch (OnSaveNotImplementedException)
                    {
                        OldOnSaveTrampoline(input, output, token, callback);
                    }
                }

                if (disposeMe != null)
                {
                    disposeMe.Dispose();
                    disposeMe = null;
                }
            }
        }
 /// <summary>
 /// Rotates an image by the given angle in degrees.
 /// </summary>
 /// <param name="source">The image to resize.</param>
 /// <param name="degrees">The angle in degrees to perform the rotation.</param>
 /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
 /// <returns>The <see cref="Image"/></returns>
 public static Image Rotate(this Image source, float degrees, ProgressEventHandler progressHandler = null)
 {
     return Rotate(source, degrees, new BicubicResampler(), progressHandler);
 }
示例#60
0
        public static Document LoadDocument(Control owner, string fileName, out FileType fileTypeResult, ProgressEventHandler progressCallback)
        {
            FileTypeCollection fileTypes;
            int ftIndex;
            FileType fileType;

            fileTypeResult = null;

            try
            {
                fileTypes = FileTypes.GetFileTypes();
                ftIndex = fileTypes.IndexOfExtension(Path.GetExtension(fileName));

                if (ftIndex == -1)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ImageTypeNotRecognized"));
                    return null;
                }

                fileType = fileTypes[ftIndex];
                fileTypeResult = fileType;
            }

            catch (ArgumentException)
            {
                string format = PdnResources.GetString("LoadImage.Error.InvalidFileName.Format");
                string error = string.Format(format, fileName);
                Utility.ErrorBox(owner, error);
                return null;
            }

            Document document = null;

            using (new WaitCursorChanger(owner))
            {
                Utility.GCFullCollect();
                Stream stream = null;

                try
                {
                    try
                    {
                        stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        long totalBytes = 0;

                        SiphonStream siphonStream = new SiphonStream(stream);

                        IOEventHandler ioEventHandler = null;
                        ioEventHandler =
                            delegate(object sender, IOEventArgs e)
                            {
                                if (progressCallback != null)
                                {
                                    totalBytes += (long)e.Count;
                                    double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
                                    progressCallback(null, new ProgressEventArgs(percent));
                                }
                            };

                        siphonStream.IOFinished += ioEventHandler;

                        using (new WaitCursorChanger(owner))
                        {
                            document = fileType.Load(siphonStream);

                            if (progressCallback != null)
                            {
                                progressCallback(null, new ProgressEventArgs(100.0));
                            }
                        }

                        siphonStream.IOFinished -= ioEventHandler;
                        siphonStream.Close();
                    }

                    catch (WorkerThreadException ex)
                    {
                        Type innerExType = ex.InnerException.GetType();
                        ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });

                        if (ci == null)
                        {
                            throw;
                        }
                        else
                        {
                            Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
                            throw ex2;
                        }
                    }
                }

                catch (ArgumentException)
                {
                    if (fileName.Length == 0)
                    {
                        Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
                    }
                    else
                    {
                        Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
                    }
                }

                catch (UnauthorizedAccessException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
                }

                catch (SecurityException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
                }

                catch (FileNotFoundException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
                }

                catch (DirectoryNotFoundException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
                }

                catch (PathTooLongException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
                }

                catch (IOException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
                }

                catch (SerializationException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
                }

                catch (OutOfMemoryException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
                }

                catch (Exception)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
                }

                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                }
            }

            return document;
        }