public static void CreateInstance() { var bucketName = "ec2-sample-" + RESOURCDE_POSTFIX; var ec2Client = new AmazonEC2Client(); // Get latest 2012 Base AMI var imageId = ImageUtilities.FindImage(ec2Client, ImageUtilities.WINDOWS_2012_BASE).ImageId; Console.WriteLine("Using Image ID: {0}", imageId); var runRequest = new RunInstancesRequest { ImageId = imageId, MinCount = 1, MaxCount = 1, InstanceType = new InstanceType("t1.micro") }; var instanceId = ec2Client.RunInstances(runRequest).Reservation.Instances[0].InstanceId; ec2Client.CreateTags(new CreateTagsRequest { Resources = new List <string> { instanceId }, Tags = new List <Amazon.EC2.Model.Tag> { new Amazon.EC2.Model.Tag { Key = "Name", Value = "Processor" } } }); Console.WriteLine("Adding Name Tag to instance"); // Pause to be sure instance has started Thread.Sleep(45000); ec2Client.StopInstances(new StopInstancesRequest { InstanceIds = new List <string> { instanceId } }); }
private void button6_Click(object sender, EventArgs e) { ts = new TimeSpan(DateTime.Now.Ticks); textBox1.Text = ""; showTimeStamp("Process Started"); if (!loadLast_cb.Checked) { panel1.BackgroundImage = System.Drawing.Image.FromFile(filenamet.Text); } showTimeStamp("Image Read"); panel1.BackgroundImage = (System.Drawing.Image)ImageUtilities.ResizeImage((Bitmap)panel1.BackgroundImage, 2100, 2100 * panel1.BackgroundImage.Height / panel1.BackgroundImage.Width); panel1.Invalidate(); Application.DoEvents(); showTimeStamp("Resized"); Application.DoEvents(); Bitmap unf = new Bitmap(panel1.BackgroundImage); OpticalReader reader = new OpticalReader(); panel1.BackgroundImage = (System.Drawing.Image)reader.ExtractOMRSheet(unf, "sheets.xml", OMREnums.OMRSheet.A550); showTimeStamp("OMR Extraction Finished"); panel1.Invalidate(); }
private void OpenFileMenuItem_Click(object sender, EventArgs e) { openFileDialog1.InitialDirectory = @"c:\Users\tmaszczyk\Dropbox\PUZZLE"; openFileDialog1.FileName = ""; DialogResult result = openFileDialog1.ShowDialog(this); if (result == DialogResult.OK) { if (!String.IsNullOrEmpty(openFileDialog1.FileName)) { if (_sourcePicture != null) { _sourcePicture.Dispose(); } _sourcePicture = new Bitmap(openFileDialog1.FileName); // Resize the picture to fit the desired dimensions if it is too large. if (_sourcePicture.Width > _puzzlePictureWidth || _sourcePicture.Height > _puzzlePictureHeight) { _sourcePicture = ImageUtilities.ResizeImage(_sourcePicture, _puzzlePictureWidth, _puzzlePictureHeight, false); } // Create and display jigsaw puzzle ResponseMessage responseMsg = CreateJigsawPuzzle(); if (!responseMsg.Okay) { _sourcePicture.Dispose(); MessageBox.Show(responseMsg.Message); return; } DisplayJigsawPuzzle(Settings.Default.ShowImageHint); _victoryAnnounced = false; } } }
//************************************** /*IMPORTED ALL*/ private bool ProcessImage() { ts = new TimeSpan(DateTime.Now.Ticks); sMsg = "Extracting OMR image..."; panel.Invalidate(); Application.DoEvents(); imgsrc = ImageUtilities.ResizeImage(imgsrc, 2100, 2100 * imgsrc.Height / imgsrc.Width); showTimeStamp("Resized", true); Bitmap unf = new Bitmap(imgsrc); Application.DoEvents(); panel.Image = (System.Drawing.Image)opr.ExtractOMRSheet(unf, 0, 0); Graphics gx = Graphics.FromImage(panel.Image); if (opr.lExtractResult == OpticalReader.ExtractResults.FAILED) { sMsg = "Failed acquiring OMR source."; panel.Invalidate(); showTimeStamp("Extraction Failed.", true); return(false); } if (opr.lExtractResult == OpticalReader.ExtractResults.INVALIDAR) { sMsg = "Invalid OMR source."; panel.Invalidate(); showTimeStamp("OMR source and sheet size do not match.", true); return(false); } foreach (Rectangle ri in opr.rBlocks) { gx.DrawRectangle(pn, ri); } sMsg = "OMR extraction complete."; panel.Invalidate(); showTimeStamp("Successful OMR Extraction.", true); return(true); }
protected void Page_Load(object sender, EventArgs e) { BookTBx book = new BookTBx(); BookManager bm = new BookManager(); book.Name = Request["name"]; book.ShortDesc = Request["shortdesc"]; book.Desc = Request["desc"]; book.Price = Convert.ToInt32(Request["price"]); book.Status = 1; bm.AddNew(book); ImageManager IM = new ImageManager(); string base64 = Request["base64"]; //Nut tải ảnh lên if (base64 != "" && base64 != null) { var imagebase64 = ImageUtilities.ConvertBase64ToImage(base64); var extention = ImageUtilities.getExtention(imagebase64.RawFormat); imagebase64 = ImageUtilities.CreateThumbnail2(1024, 800, imagebase64); ImageTBx ima = new ImageTBx(); ima.Name = "demo.jpg"; ima.BookID = book.ID; IM.AddNew(ima); ima.Name = "sach_" + ima.ID + extention; IM.Save(); imagebase64.Save(Server.MapPath("~/upload/" + ima.Name), imagebase64.RawFormat); var imagethumb = ImageUtilities.CreateThumbnail(300, 500, Server.MapPath("~/upload/" + ima.Name)); imagethumb.Save(Server.MapPath("~/upload/thumbnails/" + ima.Name), imagethumb.RawFormat); imagethumb.Dispose(); } bm.Save(); return; }
public void TestFindMinimumAreaSpottedDiagonal() { // Test a bitmap with two plots that define a minimum rectangle: // ------------ // ------------ // --------[]-- // ------------ // ----[]------ // ------------ // Create the bitmap Bitmap bitmap = new Bitmap(6, 6); FillBitmapRegion(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Transparent); // Add the two plots bitmap.SetPixel(4, 2, Color.Red); bitmap.SetPixel(2, 4, Color.Red); // Test the resulting area rectangle Rectangle bitmapArea = ImageUtilities.FindMinimumImageArea(bitmap); Assert.AreEqual(new Rectangle(2, 2, 3, 3), bitmapArea, "The minimum image area has to clip around the opaque pixels"); }
public static void TrainBrain(Brain brain, string Filename, int ExpectedOutput) { Bitmap bmp = new Bitmap(Filename); if (bmp.Width > 64 || bmp.Height > 64) { bmp = ImageUtilities.ResizeImage(bmp, new Size(64, 64)); } List <double> Inputs = new List <double>(); double[] ExpectedOutputs = new double[1]; ExpectedOutputs[0] = ExpectedOutput; for (int y = 0; y < bmp.Height - 1; y++) { for (int x = 0; x < bmp.Width; x++) { Color oc = bmp.GetPixel(x, y); Inputs.Add(oc.GetHue() + oc.GetSaturation() + oc.GetBrightness()); } } brain.Train(Inputs.ToList(), ExpectedOutputs.ToList()); }
private async Task RotateImage(int blogEntryId, string photoUrl) { var folderPath = GetBlogPhotoFolder(blogEntryId); var stream = await _imageUploaderService.ToStreamAsync(photoUrl); var imageHelper = new ImageUtilities(); const float angle = 90; var rotatedBitmap = imageHelper.RotateImage(Image.FromStream(stream), angle); Image fullPhoto = rotatedBitmap; var streamRotated = _imageUploaderService.ToAStream(fullPhoto, _imageUploaderService.SetImageFormat(photoUrl)); await _siteFilesRepository.UploadAsync( streamRotated, photoUrl.GetFileNameFromUrl(), folderPath); fullPhoto.Dispose(); streamRotated.Dispose(); rotatedBitmap.Dispose(); }
/// <summary> /// Applies the layer rendering on a given set of bitmaps /// </summary> /// <param name="bitmap">The bitmap to apply the layer rendering on</param> /// <param name="side">Specifies which side of the layers to draw</param> private void ApplyOnBitmap(Bitmap bitmap, LayerSide side) { // Iterate through and render each layer up to the current layer IFrameLayer[] layers = _layerController.FrameLayers; int min = (side == LayerSide.BottomLayers ? 0 : _layerController.ActiveLayerIndex + 1); int max = (side == LayerSide.BottomLayers ? _layerController.ActiveLayerIndex : layers.Length); for (int i = min; i < max; i++) { if (_layerStatuses[i].Visible && _layerStatuses[i].Transparency > 0) { var layerBitmap = layers[i].LayerBitmap; if (_layerStatuses[i].Transparency >= 1) { ImageUtilities.FlattenBitmaps(bitmap, layerBitmap, false); } else { using (Graphics g = Graphics.FromImage(bitmap)) { var cm = new ColorMatrix { Matrix33 = _layerStatuses[i].Transparency }; ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(layerBitmap, new Rectangle(Point.Empty, layerBitmap.Size), 0, 0, layerBitmap.Width, layerBitmap.Height, GraphicsUnit.Pixel, attributes); g.Flush(); } } } } }
public IImage Apply(IImage sourceImage) { if (!width.HasValue && !height.HasValue && !horizontalScale.HasValue && !verticalScale.HasValue) { return(sourceImage); } if (options == ImageSizingMode.ResizeIfLarger) { if ((!width.HasValue || sourceImage.Width <= width.Value) && (!height.HasValue || sourceImage.Height <= height.Value)) { return(sourceImage); } } if (options == ImageSizingMode.ResizeIfSmaller) { if ((!width.HasValue || sourceImage.Width >= width.Value) && (!height.HasValue || sourceImage.Height >= height.Value)) { return(sourceImage); } } int?newWidth = width; int?newHeight = height; if (!newWidth.HasValue && horizontalScale.HasValue) { newWidth = (int)(sourceImage.Width * horizontalScale.Value); } if (!newHeight.HasValue && verticalScale.HasValue) { newHeight = (int)(sourceImage.Height * verticalScale.Value); } return(Image.FromBitmap(ImageUtilities.ResizeImage(sourceImage.ToBitmap(disposeOriginal: true), newWidth, newHeight, disposeOriginal: true))); }
/// <summary> /// Properly resizes any size bitmap to the keyboard by creating a rectangle whose size is dependent on the bitmap /// size. /// </summary> /// <param name="bitmap"></param> public override void DrawBitmap(Bitmap bitmap) { var image = ImageUtilities.ResizeImage(bitmap, Width, Height); // For STRAFE, stretch the image on row 2. if (_keyboard.DeviceInfo.Model == "STRAFE RGB") { var strafeBitmap = new Bitmap(22, 8); using (var g = Graphics.FromImage(strafeBitmap)) { g.DrawImage(image, new Point(0, 0)); g.DrawImage(image, new Rectangle(0, 3, 22, 7), new Rectangle(0, 2, 22, 7), GraphicsUnit.Pixel); } image.Dispose(); image = strafeBitmap; } _keyboardBrush.Image = image; _keyboard.Update(); image.Dispose(); }
public static async Task <string> CreateInstance(AmazonEC2Client ec2Client, string imageId, string KeyName, string instanceName) { var image = await ImageUtilities.FindImageAsync(ec2Client, ImageUtilities.WINDOWS_2012_BASE); Console.WriteLine($"Search for image id using {imageId} and found {image.ImageId}"); var runRequest = new RunInstancesRequest { ImageId = image.ImageId, MinCount = 1, MaxCount = 1, KeyName = KeyName }; var response = await ec2Client.RunInstancesAsync(runRequest); var instanceId = response.Reservation.Instances[0].InstanceId; if (!string.IsNullOrWhiteSpace(instanceName)) { await NameInstance(ec2Client, instanceId, instanceName); } Console.WriteLine($"Instance Id: {instanceId}"); return(instanceId); }
public static void LoadPluginTabItem(PluginInstance pluginInstance) { try { var pluginName = pluginInstance.Instance.FriendlyName; if (SettingsViewModel.Instance.HomePluginList.Any(p => p.ToUpperInvariant() .StartsWith(pluginName.ToUpperInvariant()))) { pluginName = String.Format("{0}[{1}]", pluginName, new Random().Next(1000, 9999)); } SettingsViewModel.Instance.HomePluginList.Add(pluginName); var tabItem = pluginInstance.Instance.CreateTab(); tabItem.Name = Regex.Replace(pluginInstance.Instance.Name, @"[^A-Za-z]", ""); var iconfile = String.Format("{0}\\{1}", Path.GetDirectoryName(pluginInstance.AssemblyPath), pluginInstance.Instance.Icon); var icon = new BitmapImage(new Uri(Common.Constants.DefaultIcon)); icon = File.Exists(iconfile) ? ImageUtilities.LoadImageFromStream(iconfile) : icon; tabItem.HeaderTemplate = ImageHeader(icon, pluginInstance.Instance.FriendlyName); AppViewModel.Instance.PluginTabItems.Add(tabItem); } catch (Exception ex) { } }
private void trackBar1_ValueChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Properties.Settings.Default.UMFilename)) { Bitmap bmp = null; if (checkBox8.Checked) { bmp = new Bitmap(string.Equals(comboBox2.SelectedItem.ToString(), "Flat") ? new Bitmap(Resources.Template_F_F) : string.Equals(comboBox2.SelectedItem.ToString(), "Minimalist") ? new Bitmap(Resources.Template_M_F) : new Bitmap(Resources.Template_D_F)); } else { bmp = new Bitmap(string.Equals(comboBox2.SelectedItem.ToString(), "Flat") ? new Bitmap(Resources.Template_F_N) : string.Equals(comboBox2.SelectedItem.ToString(), "Minimalist") ? new Bitmap(Resources.Template_M_N) : new Bitmap(Resources.Template_D_N)); } Graphics g = Graphics.FromImage(bmp); Image watermark = Image.FromFile(Properties.Settings.Default.UMFilename); var opacityImage = ImageUtilities.SetImageOpacity(watermark, (float)trackBar1.Value / 100); g.DrawImage(ImageUtilities.ResizeImage(opacityImage, trackBar2.Value, trackBar2.Value), (522 - trackBar2.Value) / 2, (522 - trackBar2.Value) / 2, trackBar2.Value, trackBar2.Value); wPictureBox.Image = bmp; wPictureBox.Refresh(); } }
public LocationModel(Location dataModel = null) { DataModel = dataModel ?? new Location { Id = Guid.NewGuid() }; if (DataModel.Image != null) { _image = ImageUtilities.Deserialize(DataModel.Image); } if (DataModel.Realmlists != null) { var models = DataModel.Realmlists.Select(x => new RealmlistModel(x)); _realmlists = new ObservableCollection <RealmlistModel>(models); } else { _realmlists = new ObservableCollection <RealmlistModel>(); } _realmlists.CollectionChanged += Realmlists_CollectionChanged; }
public static bool ProcessImageFromFile(Brain brain, string Filename) { Bitmap bmp = new Bitmap(Filename); bmp = ImageUtilities.ResizeImage(bmp, new Size(64, 64)); List <double> Inputs = new List <double>(); for (int y = 0; y < bmp.Height - 1; y++) { for (int x = 0; x < bmp.Width; x++) { Color oc = bmp.GetPixel(x, y); Inputs.Add(oc.GetHue() + oc.GetSaturation() + oc.GetBrightness()); } } double NeuronsPerLayer = Inputs.Count; NeuronsPerLayer *= RATIO_TOP; NeuronsPerLayer /= RATIO_BOTTOM; NeuronsPerLayer += 1; List <double> Values = brain.Think(Inputs).Result; if (Values != null) { double Value = Values[0]; for (int i = 0; i < Values.Count; i++) { Program.WriteLine("FINAL RESULT[" + i + "]: " + Values[i]); } return(Value > .5 ? true : false); } else { throw new BrainFireException("Null return value."); } return(false); }
private void OpenFileMenuItem_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(this); if (result == DialogResult.OK) { if (!String.IsNullOrEmpty(openFileDialog1.FileName)) { if (_sourcePicture != null) { _sourcePicture.Dispose(); } _sourcePicture = new Bitmap(openFileDialog1.FileName); // Resize the picture to fit the desired dimensions if it is too large. if (_sourcePicture.Width > _puzzlePictureWidth || _sourcePicture.Height > _puzzlePictureHeight) { _sourcePicture = ImageUtilities.ResizeImage(_sourcePicture, _puzzlePictureWidth, _puzzlePictureHeight, false); } // Create and display jigsaw puzzle try { var gen = new PuzzleGenerater(); _clusters = gen.CreateJigsawPuzzle(this.ClientSize, _sourcePicture, menuStrip1.Height); DisplayJigsawPuzzle(Settings.Default.ShowImageHint); _victoryAnnounced = false; } catch (Exception ex) { _sourcePicture.Dispose(); MessageBox.Show(ex.Message); } } } }
public IActionResult OnPostCreate() { if (!ModelState.IsValid) { return(this.Page()); } var category = this.Context.Categories.FirstOrDefault(c => c.Name == this.Name); if (category != null) { notificationSender.SendNotification(String.Format(Constants.CategoryAlreadyExistsMessage, category.Name), MessageType.Danger, pageModel: this); return(this.Page()); } var bannerExtension = BannerUrl.Substring(BannerUrl.LastIndexOf('.')); var bannerFileName = String.Format(Constants.CategoryBannerName, this.Name, bannerExtension); var wwwRootPath = this.hostingEnvironment.WebRootPath; var bannerPath = wwwRootPath + Constants.CategoriesBannerPathFromWebRoot + bannerFileName; ImageUtilities.SaveCategoryBannerFromUrl(bannerPath, this.BannerUrl); category = new Category() { Name = this.Name, Banner = bannerFileName }; this.Context.Categories.Add(category); this.Context.SaveChangesAsync(); notificationSender.SendNotification(String.Format(Constants.CategoryCreatedMessage, category.Name), MessageType.Success, pageModel: this); return(this.Redirect("/home/index")); }
public void SaveFile() { int i; StringBuilder sb = new StringBuilder(1000); List <ColorPlus> palette = new List <ColorPlus>(); // only save colors that meet transparency thresh hold for (i = 0; i < ImageUtilities.input_palette.Count; i++) { if (ImageUtilities.input_palette[i].alpha > ImageUtilities.transparent_threshhold) { palette.Add(ImageUtilities.input_palette[i]); } } if (ImageUtilities.sort_saved_palette) { // sort colors according to current criteria palette = ImageUtilities.StepSort(palette); } sb.AppendFormat("GIMP Palette\r\nName: {0}\r\n# This file generated by Color Palette Swapper\r\n# https://williamthompsonj.github.io/Color-Palette-Swapper/\r\n#", ImageUtilities.filename); for (i = 0; i < palette.Count; i++) { // don't save transparent colors, this palette format doesn't support transparency! if (palette[i].alpha <= ImageUtilities.transparent_threshhold) { continue; } sb.AppendFormat("\r\n{0}\tindex {1}", ImageUtilities.ToGPL(palette[i].color32), 1 + i); } _data = sb.ToString(); }
public static bool ProcessImageFromFile(string BrainFile, string Filename) { Program.WriteLine("Loading brain..."); Brain brain = Brain.LoadNetwork(BrainFile); Program.WriteLine("Done loading brain"); Bitmap bmp = new Bitmap(Filename); bmp = ImageUtilities.ResizeImage(bmp, new Size(64, 64)); List <double> Inputs = new List <double>(); for (int y = 0; y < bmp.Height - 1; y++) { for (int x = 0; x < bmp.Width; x++) { Color oc = bmp.GetPixel(x, y); Inputs.Add(oc.GetHue() + oc.GetSaturation() + oc.GetBrightness()); } } int NeuronsPerLayer = Inputs.Count * ((int)RATIO_TOP / RATIO_BOTTOM); NeuronsPerLayer += 1; List <double> Values = brain.Think(Inputs).Result; if (Values != null) { double Value = Values[0]; Console.WriteLine("Value: " + Value); return(Value > .5 ? true : false); } else { throw new BrainFireException("Null return value."); } return(false); }
public override void DrawBitmap(Bitmap bitmap) { // Resize the bitmap using (var b = ImageUtilities.ResizeImage(bitmap, Width, Height)) { // Create an empty matrix var matrix = new COLOR_MATRIX { KeyColor = new KEY_COLOR[6, 22] }; // Map the bytes to the matix for (var x = 0; x < Width; x++) { for (var y = 0; y < Height; y++) { var c = b.GetPixel(x, y); matrix.KeyColor[y, x] = new KEY_COLOR(c.R, c.G, c.B); } } // Send the matrix to the keyboard CmSdk.SetAllLedColor(matrix); } }
public virtual BufferedImage processImage(BufferedImage image) { originalImage = image; int width = originalImage.Width; int height = originalImage.Height; filteredImage = new BufferedImage(width, height, originalImage.Type); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int color = findMean(i, j); int alpha = (new Color(originalImage.getRGB(i, j))).Alpha; int rgb = ImageUtilities.colorToRGB(alpha, color, color, color); filteredImage.setRGB(i, j, rgb); } } return(filteredImage); }
private void btnReset_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(openFileDialog1.FileName)) { if (_sourcePicture != null) { _sourcePicture.Dispose(); } _sourcePicture = new Bitmap(openFileDialog1.FileName); // Resize the picture to fit the desired dimensions if it is too large. if (_sourcePicture.Width > _puzzlePictureWidth || _sourcePicture.Height > _puzzlePictureHeight) { _sourcePicture = ImageUtilities.ResizeImage(_sourcePicture, _puzzlePictureWidth - grbButtons.Width, _puzzlePictureHeight - menuStrip1.Height, false); } // Create and display jigsaw puzzle try { CreateJigsawPuzzle(); DisplayJigsawPuzzle(Settings.Default.ShowImageHint); _victoryAnnounced = false; } catch (Exception ex) { _sourcePicture.Dispose(); MessageBox.Show(ex.Message); } } lblCronometro.Text = "00:00:00"; Cronometro.Enabled = true; seg = 0; min = 0; hour = 0; }
public ImageForm() { InitializeComponent(); buttonOpenImage.Click += (sender, e) => { OpenFileDialog openFileDialog = DialogUtilities.CreateOpenFileDialog(FileType.Image); DialogResult result = openFileDialog.ShowDialog(); if (result != DialogResult.OK) { return; } string fileName = openFileDialog.FileName; _baseImage = Image.FromFile(fileName); pictureBoxImage.BackgroundImage = _baseImage; }; trackBarTransparency.ValueChanged += (sender, e) => { byte newAlpha = (byte)(trackBarTransparency.Value / 100.0 * 255.0); Image newImage = ImageUtilities.ChangeTransparency(_baseImage, newAlpha); pictureBoxImage.BackgroundImage = newImage; }; }
public IEnumerator Fade() { // var sprites = GetComponentsInChildren <SpriteRenderer>(); var images = GetComponentsInChildren <Image>(); var texts = GetComponentsInChildren <TMPro.TextMeshPro>(); List <IColorable> colorables = new List <IColorable>(); foreach (var sprite in sprites) { colorables.Add(new SpriteRendererC(sprite)); } foreach (var image in images) { colorables.Add(new ImageC(image)); } foreach (var t in texts) { colorables.Add(new TMP_C(t)); } yield return(ImageUtilities.FadeToTransparent(colorables, 1f / Duration)); Game.Ctx.EnemyOperator.Destroy(GetComponent <Units.Enemies.Enemy>()); }
/// <summary> /// Function to read uncompressed TGA scanline data. /// </summary> /// <param name="src">The pointer to the buffer containing the source data.</param> /// <param name="srcPitch">Pitch of the source scan line.</param> /// <param name="dest">Destination buffer pointner</param> /// <param name="format">Format of the destination buffer.</param> /// <param name="conversionFlags">Flags used for conversion.</param> private static unsafe bool ReadUncompressed(byte *src, int srcPitch, byte *dest, BufferFormat format, TGAConversionFlags conversionFlags) { bool flipHorizontal = (conversionFlags & TGAConversionFlags.InvertX) == TGAConversionFlags.InvertX; switch (format) { case BufferFormat.R8_UNorm: case BufferFormat.B5G5R5A1_UNorm: return(ImageUtilities.CopyScanline(src, srcPitch, dest, format, flipHorizontal)); case BufferFormat.R8G8B8A8_UNorm: if ((conversionFlags & TGAConversionFlags.Expand) != TGAConversionFlags.Expand) { return(ImageUtilities.CopyScanline(src, srcPitch, dest, format, flipHorizontal)); } ImageUtilities.Expand24BPPScanLine(src, srcPitch, dest, flipHorizontal); // We're already opaque by virtue of being 24 bit. return(false); } return(false); }
public void TestLayerSwapping() { // Create a frame Bitmap layer0 = FrameGenerator.GenerateRandomBitmap(64, 64, 11); Frame frame = new Frame(null, 64, 64); frame.SetFrameBitmap(layer0); Bitmap layer1 = FrameGenerator.GenerateRandomBitmap(64, 64, 10); Bitmap layer2 = FrameGenerator.GenerateRandomBitmap(64, 64, 9); frame.AddLayer(layer1); frame.AddLayer(layer2); // Swap the layers frame.SwapLayers(0, 2); // Test layer swapping by comparing the bitmaps Assert.AreEqual(0, frame.GetLayerAt(0).Index, "A layer's index must reflect its current position on the owning frame's layer list"); Assert.AreEqual(2, frame.GetLayerAt(2).Index, "A layer's index must reflect its current position on the owning frame's layer list"); Assert.IsTrue(ImageUtilities.ImagesAreIdentical(layer2, frame.GetLayerAt(0).LayerBitmap), "The layers have not been swapped correctly"); Assert.IsTrue(ImageUtilities.ImagesAreIdentical(layer0, frame.GetLayerAt(2).LayerBitmap), "The layers have not been swapped correctly"); }
/// <summary> /// Composes the specified frame into a flat bitmap /// </summary> /// <param name="frame">The frame to compose</param> /// <param name="statuses">The layer status information to use when composing the frame</param> /// <param name="ignoreStatusTransparency">Whether to ignore the Transparency of a layer when composing</param> /// <returns>A new Bitmap object that represents the composed frame</returns> public static Bitmap ComposeFrame(Frame frame, LayerStatus[] statuses, bool ignoreStatusTransparency = false) { Bitmap bitmap = new Bitmap(frame.Width, frame.Height, PixelFormat.Format32bppArgb); for (int i = 0; i < frame.LayerCount; i++) { if (statuses[i].Visible && (ignoreStatusTransparency || statuses[i].Transparency > 0)) { var layerBitmap = frame.GetLayerAt(i).LayerBitmap; if (ignoreStatusTransparency || statuses[i].Transparency >= 1) { ImageUtilities.FlattenBitmaps(bitmap, layerBitmap, false); } else { using (Graphics g = Graphics.FromImage(bitmap)) { var cm = new ColorMatrix { Matrix33 = statuses[i].Transparency }; ImageAttributes attributes = new ImageAttributes(); attributes.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(layerBitmap, new Rectangle(Point.Empty, layerBitmap.Size), 0, 0, layerBitmap.Width, layerBitmap.Height, GraphicsUnit.Pixel, attributes); g.Flush(); } } } } return(bitmap); }
public void DrawProfile <T>(Graphics keyboard, Rect keyboardRect, IDataModel dataModel, bool preview, bool updateAnimations) { var visual = new DrawingVisual(); using (var c = visual.RenderOpen()) { // Setup the DrawingVisual's size c.PushClip(new RectangleGeometry(keyboardRect)); c.DrawRectangle(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), null, keyboardRect); // Draw the layers foreach (var layerModel in Layers.OrderByDescending(l => l.Order)) { layerModel.Draw(dataModel, c, preview, updateAnimations); } // Remove the clip c.Pop(); } using (Bitmap bmp = ImageUtilities.DrawinVisualToBitmap(visual, keyboardRect)) keyboard.DrawImage(bmp, new PointF(0, 0)); }
public void Generate() { ImageUtilities.ResizeImage(InputPath, OutputPath, Width, Height, Margin); }