コード例 #1
0
        public static Image memory(
            byte[] bytes,
            Key key                  = null,
            float scale              = 1.0f,
            float?width              = null,
            float?height             = null,
            Color color              = null,
            BlendMode colorBlendMode = BlendMode.srcIn,
            BoxFit?fit               = null,
            Alignment alignment      = null,
            ImageRepeat repeat       = ImageRepeat.noRepeat,
            Rect centerSlice         = null,
            bool gaplessPlayback     = false,
            FilterMode filterMode    = FilterMode.Point
            )
        {
            var memoryImage = new MemoryImage(bytes, scale);

            return(new Image(
                       key,
                       memoryImage,
                       width,
                       height,
                       color,
                       colorBlendMode,
                       fit,
                       alignment,
                       repeat,
                       centerSlice,
                       gaplessPlayback,
                       filterMode
                       ));
        }
コード例 #2
0
        public async virtual Task <MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
        {
            MemoryImage?image = null;

            try
            {
                using var response = await http.GetAsync(this.ThumbnailImageUrl, cancellationToken)
                                     .ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                using var imageStream = await response.Content.ReadAsStreamAsync()
                                        .ConfigureAwait(false);

                image = await MemoryImage.CopyFromStreamAsync(imageStream)
                        .ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();

                return(image);
            }
            catch (OperationCanceledException)
            {
                image?.Dispose();
                throw;
            }
        }
コード例 #3
0
        private static bool ValidateFileToFlash(MemoryImage flashImage, MemoryLayout flashLayout, out string error)
        {
            error = null;

            if (flashImage != null)
            {
                if (flashImage.EndAddress % 2 != 0)
                {
                    error = "File to flash size must be an even number of bytes";
                }
                else if (flashImage.StartAddress % 2 != 0)
                {
                    error = "File to flash start address must be an even number of bytes";
                }
                else if ((flashLayout != null) && (flashLayout.Validate()) && (flashImage.Size != flashLayout.EndAddress - flashLayout.BaseAddress))
                {
                    error = "File to flash size does not match memory layout size";
                }
            }
            else
            {
                error = "File to flash is unset";
            }

            return(error == null);
        }
コード例 #4
0
ファイル: Mac65Assert.cs プロジェクト: JakubLinhart/Mac65
        internal static void OpCodes(MemoryImage actualImage, params MemoryChunk[] expectedChunks)
        {
            string message = null;

            if (actualImage.Chunks.Count() != expectedChunks.Length)
            {
                Assert.Fail("expected and actual chunk count doesn't match, expected {0}, actual is {1}",
                    expectedChunks.Length, actualImage.Chunks.Count());
            }

            var i = 0;
            foreach (var actualChunk in actualImage.Chunks)
            {
                var expectedChunk = expectedChunks[i];

                if (actualChunk.StartAddress != expectedChunk.StartAddress)
                {
                    Assert.Fail("expected chunk start address is {0} but actual is {1}", expectedChunk.StartAddress.ToString("X4"),
                        actualChunk.StartAddress.ToString("X4"));
                }

                OpCodes(actualChunk, expectedChunk);
                i++;
            }
        }
コード例 #5
0
ファイル: XexFile.cs プロジェクト: JakubLinhart/Mac65
 public static void Write(MemoryImage image, string fileName)
 {
     using (var writeStream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
     {
         Write(image, writeStream);
     }
 }
コード例 #6
0
        public static bool ValidateChecksums(byte[] imageToCheck, out bool areChecksumsCorrect, out uint numChecksums, out uint numIncorrectChecksums)
        {
            areChecksumsCorrect   = false;
            numChecksums          = 0;
            numIncorrectChecksums = 0;

            uint baseAddress;
            IEnumerable <BaseChecksum> detectedChecksums;

            if (DetectChecksums(imageToCheck, out baseAddress, out detectedChecksums))
            {
                numChecksums = (uint)detectedChecksums.Count();

                var memImageToCheck = new MemoryImage(imageToCheck, baseAddress);

                foreach (var checksum in detectedChecksums)
                {
                    checksum.SetMemoryReference(memImageToCheck);

                    if (!checksum.IsCorrect(false))
                    {
                        numIncorrectChecksums++;
                    }
                }

                areChecksumsCorrect = (numIncorrectChecksums == 0);

                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #7
0
        /// <summary>
        /// pic.twitter.com アップロード時に JPEG への変換を回避するための加工を行う
        /// </summary>
        /// <remarks>
        /// pic.twitter.com へのアップロード時に、アルファチャンネルを持たない PNG 画像が
        /// JPEG 形式に変換され画質が低下する問題を回避します。
        /// PNG 以外の画像や、すでにアルファチャンネルを持つ PNG 画像に対しては何もしません。
        /// </remarks>
        /// <returns>加工が行われた場合は true、そうでない場合は false</returns>
        private bool AddAlphaChannelIfNeeded(Image origImage, out MemoryImage newImage)
        {
            newImage = null;

            // PNG 画像以外に対しては何もしない
            if (origImage.RawFormat.Guid != ImageFormat.Png.Guid)
            {
                return(false);
            }

            using (var bitmap = new Bitmap(origImage))
            {
                // アルファ値が 255 以外のピクセルが含まれていた場合は何もしない
                foreach (var x in Enumerable.Range(0, bitmap.Width))
                {
                    foreach (var y in Enumerable.Range(0, bitmap.Height))
                    {
                        if (bitmap.GetPixel(x, y).A != 255)
                        {
                            return(false);
                        }
                    }
                }

                // 左上の 1px だけアルファ値を 254 にする
                var pixel    = bitmap.GetPixel(0, 0);
                var newPixel = Color.FromArgb(pixel.A - 1, pixel.R, pixel.G, pixel.B);
                bitmap.SetPixel(0, 0, newPixel);

                // MemoryImage 作成時に画像はコピーされるため、この後 bitmap は破棄しても問題ない
                newImage = MemoryImage.CopyFromImage(bitmap);

                return(true);
            }
        }
コード例 #8
0
ファイル: XexFile.cs プロジェクト: JakubLinhart/Mac65
 public static void Write(MemoryImage image, FileStream writeStream)
 {
     foreach (var chunk in image.Chunks)
     {
         Write(chunk, writeStream);
     }
 }
コード例 #9
0
        public static Matrix LoadImage2(string filename)
        {
            Image fileImage = Image.FromFile(filename);

            if (!(fileImage is Bitmap))
            {
                throw new InvalidOperationException("The file is not in the correct format");
            }

            Bitmap      bitmap = (Bitmap)fileImage;
            MemoryImage image  = new MemoryImage(bitmap);

            int i;
            int j;

            image.CopyBitmapToPixels();

            Matrix matrix = new Matrix(image.Height, image.Width);

            for (i = 0; i < image.Height; i++)
            {
                for (j = 0; j < image.Width; j++)
                {
                    int argb = image[i, j].ToArgb();

                    matrix[i, j] = (argb & 0x00FFFFFF);
                }
            }

            return(matrix);
        }
コード例 #10
0
        private unsafe byte[] LoadImage(MemoryImage image, FilterFunc filter = null)
        {
            using var originalMat = Mat.FromImageData(image.Content.ToArray(), ImreadModes.Unchanged);
            using var mat         = originalMat.Flip(FlipMode.X);

            if (filter != null)
            {
                if (mat.Channels() == 3)
                {
                    mat.ForEachAsVec3b((p, pos) =>
                    {
                        // We marshal a Vec3b as Vec4b which is dangerous
                        filter(ref Unsafe.AsRef <Vec4b>(p));
                    });
                }
                else if (mat.Channels() == 4)
                {
                    mat.ForEachAsVec4b((p, pos) => { filter(ref Unsafe.AsRef <Vec4b>(p)); });
                }
                else
                {
                    throw new Exception($"Unsupported channel count {mat.Channels()}");
                }
            }


            using var memory = new MemoryStream();
            mat.WriteToStream(memory);

            return(memory.ToArray());
        }
コード例 #11
0
 /// <summary>
 /// Draw this <see cref="DoubleBufferedGraphics"/> to the supplied <see cref="System.Drawing.Graphics"/>
 /// </summary>
 /// <param name="graphics"></param>
 public void Render(Graphics graphics)
 {
     if (MemoryImage != null)
     {
         // TODO: I think the rectangles are backwards on this. Should it autoscale?
         graphics.DrawImage(MemoryImage, MemoryImage.GetRectangle(), 0, 0, Size.Width, Size.Height, GraphicsUnit.Pixel);
     }
 }
コード例 #12
0
ファイル: Imaging.cs プロジェクト: wowjinxy/C64Studio
 internal void ImageToClipboard(MemoryImage Image, Rectangle Selection)
 {
     if ((Image == null) ||
         (Selection == null))
     {
         return;
     }
     ImageToClipboard(Image, Selection.X, Selection.Y, Selection.Width, Selection.Height);
 }
コード例 #13
0
        public string WriteImage(string assetName, MemoryImage image)
        {
            var callback = this.ImageWriteCallback;

            if (callback == null)
            {
                callback = (ctx, apath, img) => { ctx.WriteAllBytesToEnd(apath, img._GetBuffer()); return(apath); }
            }
            ;

            return(callback(this, assetName, image));
        }
コード例 #14
0
        public async virtual Task <MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
        {
            using (var response = await http.GetAsync(this.ThumbnailUrl, cancellationToken).ConfigureAwait(false))
            {
                response.EnsureSuccessStatusCode();

                using (var imageStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    return(await MemoryImage.CopyFromStreamAsync(imageStream)
                           .ConfigureAwait(false));
                }
            }
        }
コード例 #15
0
        public static FadeInImage memoryNetwork(
            byte[] placeholder,
            string image,
            Key key = null,
            ImageErrorWidgetBuilder placeholderErrorBuilder = null,
            ImageErrorWidgetBuilder imageErrorBuilder       = null,
            float placeholderScale   = 1.0f,
            float imageScale         = 1.0f,
            TimeSpan?fadeOutDuration = null,
            Curve fadeOutCurve       = null,
            TimeSpan?fadeInDuration  = null,
            Curve fadeInCurve        = null,
            float?width  = null,
            float?height = null,
            BoxFit?fit   = null,
            AlignmentGeometry alignment = null,
            ImageRepeat repeat          = ImageRepeat.noRepeat,
            bool matchTextDirection     = false,
            int?placeholderCacheWidth   = null,
            int?placeholderCacheHeight  = null,
            int?imageCacheWidth         = null,
            int?imageCacheHeight        = null
            )
        {
            alignment       = alignment ?? Alignment.center;
            fadeOutDuration = fadeOutDuration ?? TimeSpan.FromMilliseconds(300);
            fadeOutCurve    = fadeOutCurve ?? Curves.easeOut;
            fadeInDuration  = fadeInDuration ?? TimeSpan.FromMilliseconds(700);
            fadeInCurve     = fadeInCurve ?? Curves.easeIn;
            ImageProvider memoryImage  = new MemoryImage(placeholder, placeholderScale);
            ImageProvider networkImage = new NetworkImage(image, imageScale);

            //placeholder = ResizeImage.resizeIfNeeded(placeholderCacheWidth, placeholderCacheHeight, memoryImage);
            //image = ResizeImage.resizeIfNeeded(imageCacheWidth, imageCacheHeight, networkImage);
            return(new FadeInImage(
                       placeholder: ResizeImage.resizeIfNeeded(placeholderCacheWidth, placeholderCacheHeight, memoryImage),
                       placeholderErrorBuilder: placeholderErrorBuilder,
                       image: ResizeImage.resizeIfNeeded(imageCacheWidth, imageCacheHeight, networkImage),
                       imageErrorBuilder: imageErrorBuilder,
                       fadeOutDuration: fadeOutDuration,
                       fadeOutCurve: fadeOutCurve,
                       fadeInDuration: fadeInDuration,
                       fadeInCurve: fadeInCurve,
                       width: width, height: height,
                       fit: fit,
                       alignment: alignment,
                       repeat: repeat,
                       matchTextDirection: matchTextDirection,
                       key: key
                       ));
        }
コード例 #16
0
        /// <summary>
        /// Release all resources used by this <see cref="DoubleBufferedGraphics"/>.
        /// </summary>
        public void Dispose()
        {
            if (MemoryImage != null)
            {
                MemoryImage.Dispose();
                MemoryImage = null;
            }

            if (Graphics != null)
            {
                Graphics.Dispose();
                Graphics = null;
            }
        }
コード例 #17
0
        public static bool CorrectChecksums(byte[] imageToCheck, out uint numChecksums, out uint numCorrectedChecksums)
        {
            //TODO: make sure we are actually updating checksum data and not some random data

            numCorrectedChecksums = 0;
            numChecksums          = 0;

            uint baseAddress;
            IEnumerable <BaseChecksum> detectedChecksums;

            if (DetectChecksums(imageToCheck, out baseAddress, out detectedChecksums))
            {
                numChecksums = (uint)detectedChecksums.Count();

                var memImageToCheck = new MemoryImage(imageToCheck, baseAddress);

                foreach (var checksum in detectedChecksums)
                {
                    checksum.SetMemoryReference(memImageToCheck);

                    if (checksum.UpdateChecksum(true) && checksum.CommitChecksum())
                    {
                        numCorrectedChecksums++;
                    }
                }

                bool corrected = (numChecksums == numCorrectedChecksums);

                if (corrected)
                {
                    foreach (var checksum in detectedChecksums)
                    {
                        checksum.SetMemoryReference(memImageToCheck);

                        if (!checksum.IsCorrect(false))
                        {
                            corrected = false;
                            break;
                        }
                    }
                }

                return(corrected);
            }
            else
            {
                return(false);
            }
        }
コード例 #18
0
ファイル: TonTwitterCom.cs プロジェクト: shmdt2020/OpenTween
            public override Task <MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
            {
                return(Task.Run(async() =>
                {
                    var apiConnection = TonTwitterCom.GetApiConnection !();

                    using var imageStream = await apiConnection.GetStreamAsync(new Uri(this.ThumbnailImageUrl), null)
                                            .ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    return await MemoryImage.CopyFromStreamAsync(imageStream)
                    .ConfigureAwait(false);
                }, cancellationToken));
            }
コード例 #19
0
        private bool SaveECUFlashFile(MemoryImage readMemory)
        {
            //save the read data
            var dialog = new SaveFileDialog();

            dialog.DefaultExt      = FLASH_FILE_EXT;       //gets long extensions to work properly when they are added to a filename when saved
            dialog.Filter          = FLASH_FILE_FILTER;
            dialog.AddExtension    = true;
            dialog.OverwritePrompt = true;
            dialog.Title           = "Select Where to Save Read Flash File";

            string flashSaveLocation = null;

            if ((FileNameToFlash != null) && (FileNameToFlash.Length > 0))
            {
                var dirInfo = Directory.GetParent(FileNameToFlash);

                if (dirInfo != null)
                {
                    flashSaveLocation = dirInfo.FullName;
                }
            }

            if (string.IsNullOrEmpty(flashSaveLocation))
            {
                flashSaveLocation = Directory.GetCurrentDirectory();
            }

            dialog.InitialDirectory = flashSaveLocation;

            if (dialog.ShowDialog() == true)
            {
                if (readMemory.SaveToFile(dialog.FileName))
                {
                    App.DisplayStatusMessage("Saved ECU flash memory to: " + dialog.FileName, StatusMessageType.USER);
                }
                else
                {
                    App.DisplayStatusMessage("Failed to save ECU flash memory to file", StatusMessageType.USER);
                }
            }
            else
            {
                App.DisplayStatusMessage("Not saving ECU flash memory because user cancelled", StatusMessageType.USER);
            }

            return(true);
        }
コード例 #20
0
        public FlashingControl()
        {
            FlashMemoryImage  = new MemoryImage();
            FlashMemoryLayout = null;

            IsFlashFileOK    = false;
            IsMemoryLayoutOK = false;

            FileNameToFlash      = "";
            MemoryLayoutFileName = "";

            InitializeComponent();

            MemoryLayoutFileName = Properties.Settings.Default.MemoryLayoutFile;
            FileNameToFlash      = Properties.Settings.Default.FlashFile;
        }
コード例 #21
0
ファイル: MapThumbOSM.cs プロジェクト: togtog/OpenTween
        /// <summary>指定されたタイル番号のタイル画像を読み込むメソッド</summary>
        private async Task <MemoryImage> LoadTileImageAsync(HttpClient http, Point pos)
        {
            var tileUrl = TileServerBase + $"/{this.Zoom}/{pos.X}/{pos.Y}.png";

            using (var stream = await http.GetStreamAsync(tileUrl).ConfigureAwait(false))
            {
                MemoryImage result = null;
                try
                {
                    result = await MemoryImage.CopyFromStreamAsync(stream).ConfigureAwait(false);

                    return(result);
                }
                catch { result?.Dispose(); throw; }
            }
        }
コード例 #22
0
        /// <summary>
        /// Reset this <see cref="DoubleBufferedGraphics"/>.
        /// </summary>
        public void Reset()
        {
            if (MemoryImage != null)
            {
                MemoryImage.Dispose();
                MemoryImage = null;
            }

            if (Graphics != null)
            {
                Graphics.Dispose();
                Graphics = null;
            }

            MemoryImage = new Bitmap(Size.Width, Size.Height);
            Graphics    = Graphics.FromImage(MemoryImage);
        }
コード例 #23
0
ファイル: Pixiv.cs プロジェクト: shmdt2020/OpenTween
            public async override Task <MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
            {
                var request = new HttpRequestMessage(HttpMethod.Get, this.ThumbnailImageUrl);

                request.Headers.Add("User-Agent", Networking.GetUserAgentString(fakeMSIE: true));
                request.Headers.Referrer = new Uri(this.MediaPageUrl);

                using var response = await http.SendAsync(request, cancellationToken)
                                     .ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                using var imageStream = await response.Content.ReadAsStreamAsync()
                                        .ConfigureAwait(false);

                return(await MemoryImage.CopyFromStreamAsync(imageStream)
                       .ConfigureAwait(false));
            }
コード例 #24
0
        public static Image memory(
            byte[] bytes,
            Key key     = null,
            float scale = 1.0f,
            ImageFrameBuilder frameBuilder       = null,
            ImageErrorWidgetBuilder errorBuilder = null,
            float?width              = null,
            float?height             = null,
            Color color              = null,
            BlendMode colorBlendMode = BlendMode.srcIn,
            BoxFit?fit                  = null,
            Alignment alignment         = null,
            ImageRepeat repeat          = ImageRepeat.noRepeat,
            Rect centerSlice            = null,
            bool matchTextDirection     = false,
            bool gaplessPlayback        = false,
            FilterQuality filterQuality = FilterQuality.low,
            int?cacheWidth              = default,
            int?cacheHeight             = null
            )
        {
            // ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, MemoryImage(bytes, scale: scale));
            var memoryImage = new MemoryImage(bytes: bytes, scale: scale);

            return(new Image(
                       key: key,
                       ResizeImage.resizeIfNeeded(cacheWidth: cacheWidth, cacheHeight: cacheHeight,
                                                  new MemoryImage(bytes: bytes, scale: scale)),
                       frameBuilder: frameBuilder,
                       null,
                       errorBuilder: errorBuilder,
                       width: width,
                       height: height,
                       color: color,
                       colorBlendMode: colorBlendMode,
                       fit: fit,
                       alignment: alignment,
                       repeat: repeat,
                       centerSlice: centerSlice,
                       matchTextDirection: matchTextDirection,
                       gaplessPlayback: gaplessPlayback,
                       filterQuality: filterQuality
                       ));
        }
コード例 #25
0
        private void DockingManager_Loaded(object sender, RoutedEventArgs e)
        {
            List <LayoutAnchorable> docks = new List <LayoutAnchorable>();

            docks.Add(Background);
            docks.Add(Breakpoints);
            docks.Add(CPU);
            //docks.Add(DisplayTiming);
            docks.Add(Interrupts);
            docks.Add(InstructionHistogram);
            docks.Add(IORegisters);
            docks.Add(Memory);
            docks.Add(MemoryImage);
            //docks.Add(SoundChannelInternals);
            //docks.Add(Spectogram);
            docks.Add(SpriteLayer);
            //docks.Add(Sprites);
            docks.Add(SoundRecording);
            docks.Add(TileMap);
            docks.Add(Window);

            foreach (LayoutAnchorable dock in docks)
            {
                dock.AutoHideWidth = 500;
                dock.FloatingWidth = 500;
            }

            Background.ToggleAutoHide();
            Breakpoints.ToggleAutoHide();
            CPU.ToggleAutoHide();
            //DisplayTiming.ToggleAutoHide();
            Interrupts.ToggleAutoHide();
            InstructionHistogram.ToggleAutoHide();
            IORegisters.ToggleAutoHide();
            Memory.ToggleAutoHide();
            MemoryImage.ToggleAutoHide();
            //SoundChannelInternals.ToggleAutoHide();
            //Spectogram.ToggleAutoHide();
            SpriteLayer.ToggleAutoHide();
            //Sprites.ToggleAutoHide();
            SoundRecording.ToggleAutoHide();
            TileMap.ToggleAutoHide();
            Window.ToggleAutoHide();
        }
コード例 #26
0
        public static void SaveImage(string filename, Matrix image)
        {
            MemoryImage mem = new MemoryImage(image.ColumnCount, image.RowCount);
            //mem.Size = new Size(image.ColumnCount, image.RowCount);

            int c;
            int r;

            for (c = 0; c < mem.Width; c++)
            {
                for (r = 0; r < mem.Height; r++)
                {
                    mem[r, c] = Color.FromArgb((int)(((uint)image[r, c]) | 0xFF000000));
                }
            }

            mem.CopyPixelsToBitmap();

            mem.Bitmap.Save(filename);
        }
コード例 #27
0
        public static FadeInImage memoryNetwork(
            byte[] placeholder,
            string image,
            float placeholderScale   = 1.0f,
            float imageScale         = 1.0f,
            TimeSpan?fadeOutDuration = null,
            Curve fadeOutCurve       = null,
            TimeSpan?fadeInDuration  = null,
            Curve fadeInCurve        = null,
            float?width         = null,
            float?height        = null,
            BoxFit?fit          = null,
            Alignment alignment = null,
            ImageRepeat repeat  = ImageRepeat.noRepeat,
            Key key             = null
            )
        {
            D.assert(placeholder != null);
            D.assert(image != null);
            D.assert(fadeOutDuration != null);
            D.assert(fadeOutCurve != null);
            D.assert(fadeInDuration != null);
            D.assert(fadeInCurve != null);
            D.assert(alignment != null);
            var memoryImage  = new MemoryImage(placeholder, placeholderScale);
            var networkImage = new NetworkImage(image, imageScale);

            return(new FadeInImage(
                       memoryImage,
                       networkImage,
                       fadeOutDuration,
                       fadeOutCurve,
                       fadeInDuration,
                       fadeInCurve,
                       width, height,
                       fit,
                       alignment,
                       repeat,
                       key
                       ));
        }
コード例 #28
0
        private void LoadFlashFile()
        {
            if (FlashMemoryImage != null)
            {
                FlashMemoryImage.Reset();
            }

            IsFlashFileOK = false;
            string error = null;

            if (FlashMemoryImage == null)
            {
                error = "Internal program error";
            }
            else if (!String.IsNullOrEmpty(FileNameToFlash))
            {
                Properties.Settings.Default.FlashFile = FileNameToFlash;

                try
                {
                    var fileBytes = File.ReadAllBytes(FileNameToFlash);
                    FlashMemoryImage = new MemoryImage(fileBytes, 0);

                    ValidateFileToFlash(FlashMemoryImage, FlashMemoryLayout, out error);
                }
                catch (Exception)
                {
                    error = "Could not read flash file";
                }
            }
            else
            {
                error = "No file selected";
            }

            //force and update without setting the property
            OnPropertyChanged(new PropertyChangedEventArgs("FlashMemoryImage"));

            this["FileNameToFlash"] = error;
            IsFlashFileOK           = (error == null);
        }
コード例 #29
0
        /// <summary>
        /// This method is the preferred method of drawing a background image.
        /// It is *MUCH* faster than any of the Graphics.DrawImage() methods.
        /// Warning: The memory image and the <see cref="System.Drawing.Graphics"/> object
        /// will be reset after calling this method. This should be your first
        /// drawing operation.
        /// </summary>
        /// <param name="image">The image to draw.</param>
        public void SetBackgroundImage(Image image)
        {
            if (MemoryImage != null)
            {
                MemoryImage.Dispose();
                MemoryImage = null;
            }

            if (Graphics != null)
            {
                Graphics.Dispose();
                Graphics = null;
            }

            MemoryImage = image.Clone() as Image;

            if (MemoryImage != null)
            {
                Graphics = Graphics.FromImage(MemoryImage);
            }
        }
コード例 #30
0
ファイル: HelperWidgets.cs プロジェクト: weacw/RunTogether
        public static ImageProvider _createImageProvider(AvatarImageType imageType, string _imagePath)
        {
            ImageProvider tmp_ImageProvider = null;

            switch (imageType)
            {
            case AvatarImageType.NetWork:
                tmp_ImageProvider = new NetworkImage(_imagePath);
                break;

            case AvatarImageType.Asset:
                tmp_ImageProvider = new AssetImage(_imagePath);
                break;

            case AvatarImageType.Memory:
                byte[] bytes = File.ReadAllBytes(_imagePath);
                tmp_ImageProvider = new MemoryImage(bytes: bytes);
                break;
            }

            return(tmp_ImageProvider);
        }
コード例 #31
0
        public ActionResult AddImage(MemoryImage imageModel)
        {
            string fileName  = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
            string extension = Path.GetExtension(imageModel.ImageFile.FileName);

            fileName             = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            imageModel.ImagePath = "~/Image/" + fileName;
            fileName             = Path.Combine(Server.MapPath("~/Image/"), fileName);
            imageModel.ImageFile.SaveAs(fileName);

            _db.Images.Add(imageModel);

            try
            {
                // Your code...
                // Could also be before try if you know the exception occurs in SaveChanges

                _db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    ViewBag.ErrorMessage = ("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                            eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        ViewBag.ErrorMessage = ("- Property: \"{0}\", Error: \"{1}\"",
                                                ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(ViewBag.ErrorMessage);
            }



            return(View());
        }
コード例 #32
0
ファイル: TonTwitterCom.cs プロジェクト: kuyagic/OpenTween
            public override Task <MemoryImage> LoadThumbnailImageAsync(HttpClient http, CancellationToken cancellationToken)
            {
                // TODO: HttpClient を使用したコードに置き換えたい
                return(Task.Run(async() =>
                {
                    var oauth = new HttpOAuthApiProxy();
                    TonTwitterCom.InitializeOAuthToken(oauth);

                    Stream response = null;
                    var statusCode = oauth.GetContent("GET", new Uri(this.ThumbnailUrl), null, ref response, Networking.GetUserAgentString());

                    using (response)
                    {
                        if (statusCode != HttpStatusCode.OK)
                        {
                            throw new WebException(statusCode.ToString(), WebExceptionStatus.ProtocolError);
                        }

                        return await MemoryImage.CopyFromStreamAsync(response)
                        .ConfigureAwait(false);
                    }
                }, cancellationToken));
            }
コード例 #33
0
        public static async void ServerStatus(SoraMessage e, string target)
        {
            var    x    = _ServerRegex.Match(target);
            string host = x.Groups["host"].Value;
            ushort port = 25565;

            if (ushort.TryParse(x.Groups["port"].Value, out ushort _port))
            {
                port = _port;
            }
            ServerInfo info = new ServerInfo(host, port);
            await info.StartGetServerInfoAsync();

            if (info.State == ServerInfo.StateType.GOOD)
            {
                var sb = new StringBuilder();
                sb.AppendLine("[Minecraft Server Status]");
                sb.AppendLine($"IP: {host}:{port}");
                sb.AppendLine($"Version: {info.GameVersion}");
                sb.AppendLine($"Players: {info.CurrentPlayerCount} / {info.MaxPlayerCount}");
                sb.AppendLine($"Latency: {info.Ping}ms");
                sb.AppendLine($"MOTD:").Append(info.MOTD);
                if (info.IconData != null)
                {
                    var icon = new MemoryImage(new Bitmap(new MemoryStream(info.IconData)));
                    await e.Reply(CQCode.CQImage(icon.ToBase64File()), Environment.NewLine, sb.ToString());
                }
                else
                {
                    await e.Reply(sb.ToString());
                }
            }
            else
            {
                await e.ReplyToOriginal("未能成功获取到目标服务器的数据,可能为参数输入错误或目标已离线");
            }
        }
コード例 #34
0
ファイル: ImageCache.cs プロジェクト: praeclarum/Praeclarum
		MemoryImage SetMemoryImage (string key, UIImage uiImage, DateTime genTime)
		{
			lock (memory) {
				MemoryImage memImage;
				if (memory.TryGetValue (key, out memImage)) {
					memImage.LastAccessTime = DateTime.UtcNow;
					memImage.Image = uiImage;
					return memImage;
				}

				//
				// If not in memory, then let's make room to add it
				//
				var numToRemove = (memory.Count + 1) - MaxMemorySize;
				if (numToRemove > 0) {
					var toRemove = memory.Values.OrderBy (x => x.LastAccessTime).Take (numToRemove).ToList ();
					foreach (var r in toRemove) {
						memory.Remove (r.Key);
					}
				}

				//
				// Now add it
				//
				memImage = new MemoryImage {
					Key = key,
					Image = uiImage,
					LastAccessTime = DateTime.UtcNow,
					GeneratedTime = genTime,
				};
				memory.Add (key, memImage);
				return memImage;
			}
		}
コード例 #35
0
ファイル: Mac65Assert.cs プロジェクト: JakubLinhart/Mac65
 public static void OpCodes(MemoryImage memoryImage, params byte[] expected)
 {
     OpCodes(memoryImage.Chunks.Single(), new MemoryChunk(0, expected));
 }