Search Results

Search found 30 results on 2 pages for 'drawing2d'.

Page 1/2 | 1 2  | Next Page >

  • Create Outlines around line.

    - by Eric Muller
    Hi SO community! I am drawing graphs into a WinForms Picturebox. Now I am searching for a possibility to 'duplicate' a line (an array of points), so that the two resulting lines are positioned a fixed distance away from the original one. Like in this picture, I have the red line and want to get the black ones: I thought about just moving the line a few pixels up/right/up-right, but that leads to strange overlapping lines. Is there any other approach that does what I want? Any ideas would be greatly appreciated. Thanks!

    Read the article

  • Why does this thumbnail generation code throw OutOfMemoryException on large files?

    - by tsilb
    This code works great for generating thumbnails, but when given a very large (100MB+) TIFF file, it throws OutOfMemoryExceptions. When I do it manually in Paint.NET on the same machine, it works fine. How can I improve this code to stop throwing on very large files? In this case I'm loading a 721MB TIF on a machine with 8GB RAM. The Task Manager shows 2GB used so something is preventing it from using all that memory. Specifically it throws when I load the Image to calculate the size of the original. What gives? /// <summary>Creates a thumbnail of a given image.</summary> /// <param name="inFile">Fully qualified path to file to create a thumbnail of</param> /// <param name="outFile">Fully qualified path to created thumbnail</param> /// <param name="x">Width of thumbnail</param> /// <returns>flag; result = is success</returns> public static bool CreateThumbnail(string inFile, string outFile, int x) { // Validation - assume 16x16 icon is smallest useful size. Smaller than that is just not going to do us any good anyway. I consider that an "Exceptional" case. if (string.IsNullOrEmpty(inFile)) throw new ArgumentNullException("inFile"); if (string.IsNullOrEmpty(outFile)) throw new ArgumentNullException("outFile"); if (x < 16) throw new ArgumentOutOfRangeException("x"); if (!File.Exists(inFile)) throw new ArgumentOutOfRangeException("inFile", "File does not exist: " + inFile); // Mathematically determine Y dimension int y; using (Image img = Image.FromFile(inFile)) { // OutOfMemoryException double xyRatio = (double)x / (double)img.Width; y = (int)((double)img.Height * xyRatio); } // All this crap could have easily been Image.Save(filename, x, y)... but nooooo.... using (Bitmap bmp = new Bitmap(inFile)) using (Bitmap thumb = new Bitmap((Image)bmp, new Size(x, y))) using (Graphics g = Graphics.FromImage(thumb)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; System.Drawing.Imaging.EncoderParameters ep2 = new System.Drawing.Imaging.EncoderParameters(1); ep2.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); g.DrawImage(bmp, new Rectangle(0,0,thumb.Width, thumb.Height)); try { thumb.Save(outFile, codec, ep2); return true; } catch { return false; } } }

    Read the article

  • How to make a Non Rectangular Winforms ?

    - by karthik
    I am using the below code to change to shape of the winform. Its changing the shape, but not like how i wanted. I need the forms to have curved corners. What points should i use to get it ? public void MakeNonRectangularForm() { System.Drawing.Drawing2D.GraphicsPath p = new System.Drawing.Drawing2D.GraphicsPath(); int width = this.ClientSize.Width; int height = this.ClientSize.Height; p.AddClosedCurve(new Point[]{new Point(width/2, height/2), new Point(width,0), new Point(width, height/3), new Point(width-width/3, height), new Point(width/7, height-height/8)}); this.Region = new Region(p); }

    Read the article

  • Printing Images C# Overlapping Wrong

    - by Alen
    I have created a program much like Photoshop in the sense that you can place images (picture box) on a control, move them around, delete them, and so on... I have also managed to put together a method to print all the images on the control with no problems. But here is the weird part: When I click print, the program prints the image which was placed first, on top of the image which came second. On the screen the user can see the image which was placed second, on top of the first placed image (the way it should be) but when I print its opposite? I have no idea why it does this... I hope I've made my self as clear as possible, any help is appreciated! public void printToGraphics(Graphics graphics, Rectangle bounds) { graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Bitmap bitmap = new Bitmap(newLabel.Width, newLabel.Height); newLabel.DrawToBitmap(bitmap, newLabel.DisplayRectangle); Rectangle target = new Rectangle(0, 0, bounds.Width, bounds.Height); target.Height = bitmap.Height; target.Width = bitmap.Width; graphics.PageUnit = GraphicsUnit.Display; graphics.DrawImage(bitmap,target); } void printDoc_PrintPage(object sender, PrintPageEventArgs e) { printToGraphics(e.Graphics, e.MarginBounds); }

    Read the article

  • ASPX ajax form post help

    - by StealthRT
    Hey all, i have this peice of code that allows a user to select a jpg image, resize it and uploads it to the server driectory. The problem being is that it reloads the aspx page when it saves the image. My question is-is there any way to do this same thing but with ajax so that it doesn't leave the page after submitting it? I've done this pleanty of times with classic asp pages but never with a aspx page. Here is the code for the ASPX page: <%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%> <%@ Import Namespace=System.Drawing %> <%@ Import Namespace=System.Drawing.Imaging %> <%@ Import Namespace=System.Drawing.Text %> <%@ Import Namespace=System %> <%@ Import Namespace=System.IO %> <%@ Import Namespace=System.Web %> <%@ Import Namespace=System.ServiceProcess %> <%@ Import Namespace=Microsoft.Data.Odbc %> <%@ Import Namespace=System.Data.Odbc %> <%@ Import Namespace=MySql.Data.MySqlClient %> <%@ Import Namespace=MySql.Data %> <%@ Import Namespace=System.Drawing.Drawing2D %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.ADO" %> <%@ Import Namespace=ADODB %> <SCRIPT LANGUAGE="VBScript" runat="server"> const Lx = 200 const Ly = 60 const upload_dir = "/img/avatar/" const upload_original = "tmpAvatar" const upload_thumb = "thumb" const upload_max_size = 256 dim fileExt dim newWidth, newHeight as integer dim l2 dim fileFld as HTTPPostedFile Dim originalimg As System.Drawing.Image dim msg dim upload_ok as boolean </script> <% Dim theID, theEmail, maleOrFemale theID = Request.QueryString("ID") theEmail = Request.QueryString("eMail") maleOrFemale = Request.QueryString("MF") randomize() upload_ok = false if lcase(Request.ServerVariables("REQUEST_METHOD"))="post" then fileFld = request.files(0) if fileFld.ContentLength > upload_max_size * 1024 then msg = "Sorry, the image must be less than " & upload_max_size & "Kb" else try fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower() if fileExt = ".jpg" then originalImg = System.Drawing.Image.FromStream(fileFld.InputStream) if originalImg.Height > Ly then newWidth = Ly * (originalImg.Width / originalImg.Height) newHeight = Ly end if Dim thumb As New Bitmap(newWidth, newHeight) Dim gr_dest As Graphics = Graphics.FromImage(thumb) dim sb = new SolidBrush(System.Drawing.Color.White) gr_dest.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality gr_dest.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height) gr_dest.DrawImage(originalImg, 0, 0, thumb.Width, thumb.Height) try originalImg.save(Server.MapPath(upload_dir & upload_original & fileExt), originalImg.rawformat) thumb.save(Server.MapPath(upload_dir & theID & fileExt), originalImg.rawformat) msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt) upload_ok = true File.Delete(Server.MapPath(upload_dir & upload_original & fileExt)) catch msg = "Sorry, there was a problem saving your avatar. Please try again." end try if not thumb is nothing then thumb.Dispose() thumb = nothing end if else msg = "That image does not seem to be a JPG. Upload only JPG images." end if catch msg = "That image does not seem to be a JPG." end try end if if not originalImg is nothing then originalImg.Dispose() originalImg = nothing end if end if %><head> <meta http-equiv="pragma" content="no-cache" /> </head> <html> <script type="text/javascript" src="js/jquery-1.3.min.js"></script> <form enctype="multipart/form-data" method="post" runat="server" id="sendImg"> <input type="file" name="upload_file" id="upload_file" style="-moz-opacity: 0; opacity:0; filter: alpha(opacity=0); margin-top: 5px; float:left; cursor:pointer;" onChange="$('#sendImg').submit();" > <input type="submit" value="Upload" style="visibility:hidden; display:none;"> </form> </body> </html> Any help would be great! :o) David

    Read the article

  • How to get quality sprite sheet generation with rotations

    - by BenMaddox
    I'm working on a game that uses sprite sheets with rotation for animations. While the effect is pretty good, the quality of the rotations is somewhat lacking. I exported a flash animation to png sequence and then used a C# app to do matrix based rotations (System.Drawing.Drawing2D.Matrix). Unfortunately, there are several places where the image gets clipped. What would you suggest for a way to get high quality rotations from either flash or the exported PNGs? A circle should fit within the same image boundaries. I don't mind a new program that I must write or an existing program I must download/buy.

    Read the article

  • C#: Graphics DrawString to Exactly Place Text on a System.Label

    - by jp2code
    I have overridden the OnPaint method of my Label control in VS2008: void Label_OnPaint(object sender, PaintEventArgs e) { base.OnPaint(e); Label lbl = sender as Label; if (lbl != null) { string Text = lbl.Text; e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; if (myShowShadow) { // draw the shadow first! e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault); } e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault); } } This works, but I really want to find out how to center the text both vertically and horizontally. I've heard of the MeasureString() method, but my "Text" complicates matters because it could include page breaks. Could someone guide me with how to do this?

    Read the article

  • How to deal with color loss on GDI+ Image Resize?

    - by user125775
    Hello All, I am resizing images with C#/GDI+ using the following routing bmpOut = new Bitmap(lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight); and encoding it with the highest quality. System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameter myEncoderParameter = new EncoderParameter(qualityEncoder, 100L); However, the images that I get have significant loss of color (I am using JPG images only). The quality is perfect, but color is washed away. Do you have any idea what is goingf on? Thanks a lot in advance.

    Read the article

  • How do I draw a gradated boarder on a polygon using GDI+ via C#/WinForms?

    - by AndyJ
    Hi, I have polygons of various shapes and sizes. They have a solid fill and currently a solid border. I would like to give the polygons a gradient on their edge to soften them. So far I've tried using a Pen with a LinearGradientBrush and whilst the effect it produces is very interesting it's most defintly not what I want ;) I've looked through the System.Drawing.Drawing2D namespace but there didnt seem to be any other classes that would be applicable for this purpose. I've had a search around and the articles that i can find are mostly about creating boarders for rectangles, which are mush easier, or are irrelivent. So to summerise, does anyone have a way of drawing a gradient boarder on a polygon using GDI+?

    Read the article

  • Scale GraphicsPaths

    - by serhio
    In a form I draw a graph. This graph has some distinct paths that should have differently drawn. Say AxesPath, SalesPath, CostsPath etc... When I resize the form need I to scale every of components Paths? Take an example: Imports System.Drawing.Drawing2D Public Class Form1 Dim lineOne As GraphicsPath Dim lineTwo As GraphicsPath Dim allPaths As GraphicsPath Dim initSize As Size Public Sub New() ' This call is required by the designer. ' InitializeComponent() initSize = Me.Size lineOne = New GraphicsPath() lineTwo = New GraphicsPath() lineOne.AddLine(20.0F, 20.0F, Me.initSize.Width - 20.0F, 20.0F) lineTwo.AddLine(0.1F, 10.0F, Me.initSize.Width - 20.0F, _ Me.initSize.Height - 0.5F) allPaths = New GraphicsPath() allPaths.AddPath(lineOne, False) allPaths.AddPath(lineTwo, False) Me.ResizeRedraw = True End Sub Protected Overrides Sub OnResize(ByVal e As System.EventArgs) MyBase.OnResize(e) Dim m As New Matrix m.Scale(Me.Width / initSize.Width, Me.Height / initSize.Height) allPaths.Transform(m) initSize = Me.Size End Sub Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) MyBase.OnPaint(e) ' WORKS ' ' e.Graphics.DrawPath(Pens.GreenYellow, allPaths) ' ' DOES NOT WORK! ' e.Graphics.DrawPath(Pens.DarkGoldenrod, lineOne) e.Graphics.DrawPath(Pens.DarkMagenta, lineTwo) End Sub End Class

    Read the article

  • How do I draw a graduated border on a polygon using GDI+ via C#/WinForms?

    - by AndyJ
    I have polygons of various shapes and sizes. They have a solid fill and currently a solid border. I would like to give the polygons a gradient on their edge to soften them. So far I've tried using a Pen with a LinearGradientBrush and whilst the effect it produces is very interesting it's most definitely not what I want ;) I've looked through the System.Drawing.Drawing2D namespace but there didn't seem to be any other classes that would be applicable for this purpose. I've had a search around and the articles that I can find are mostly about creating borders for rectangles, which are mush easier, or are irrelevant. So to summarize, does anyone have a way of drawing a gradient border in on a polygon using GDI+?

    Read the article

  • Speed of interpolation algorithms, C# and C++ working together.

    - by Kaminari
    Hello. I need fast implementation of popular interpolation algorithms. I figured it out that C# in such simple algorithms will be much slower than C++ so i think of writing some native code and using it in my C# GUI. First of all i run some tests and few operations on 1024x1024x3 matrix took 32ms in C# and 4ms in C++ and that's what i basicly need. Interpolation however is not a good word because i need them only for downscaling. But the question is: Will it be faster than C# methods in Drawing2D Image outputImage = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); Graphics grPhoto = Graphics.FromImage(outputImage); grPhoto.InterpolationMode = InterpolationMode.*; //all of them grPhoto.DrawImage(bmp, new Rectangle(0, 0, destWidth, destHeight), Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); Some of these method run in 20ms and some in 80. Is there a way to do it faster?

    Read the article

  • VB.NET pinvoke declaration wrong?

    - by tmighty
    I copied and pasted the following VB.NET structure from the pinvoke website. http://www.pinvoke.net/default.aspx/Structures/BITMAPINFOHEADER.html However when I paste it into a module under the module name like this, VB.NET is telling me that a declaration is expected: Option Strict Off Option Explicit On Imports System Imports System.Diagnostics Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Runtime.InteropServices Imports System.Windows.Forms Module modDrawing StructLayout(LayoutKind.Explicit)>Public Structure BITMAPINFOHEADER <FieldOffset(0)> Public biSize As Int32 <FieldOffset(4)> Public biWidth As Int32 <FieldOffset(8)> Public biHeight As Int32 <FieldOffset(12)> Public biPlanes As Int16 <FieldOffset(14)> Public biBitCount As Int16 <FieldOffset(16)> Public biCompression As Int32 <FieldOffset(20)> Public biSizeImage As Int32 <FieldOffset(24)> Public biXPelsperMeter As Int32 <FieldOffset(28)> Public biYPelsPerMeter As Int32 <FieldOffset(32)> Public biClrUsed As Int32 <FieldOffset(36)> Public biClrImportant As Int32 End Structure Where did I go wrong, please? Thank you very much.

    Read the article

  • Determining the color of a pixel in a bitmap using C# in a WPF app

    - by DanM
    The only way I found so far is System.Drawing.Bitmap.GetPixel(), but Microsoft has warnings for System.Drawing that are making me wonder if this is the "old way" to do it. Are there any alternatives? Here's what Microsoft says about the System.Drawing namespace. I also noticed that the System.Drawing assembly was not automatically added to the references when I created a new WPF project. System.Drawing Namespace The System.Drawing namespace provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces. The Graphics class provides methods for drawing to the display device. Classes such as Rectangle and Point encapsulate GDI+ primitives. The Pen class is used to draw lines and curves, while classes derived from the abstract class Brush are used to fill the interiors of shapes. Caution Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. - http://msdn.microsoft.com/en-us/library/system.drawing.aspx

    Read the article

  • ASP.NET error on Bitmap.Save "Exception (0x80004005): A generic error occurred in GDI+."

    - by Batu
    Hi, I have a function which first reads an image from disk, resizes it and then saves to another directory. when i use the Bitmap.Save(directory + theimagename) it returns the error as i stated in the question title. i checked the directory is right, and the given image name doesn't exist in that dir. what is weird, is that the same code works great on the local machine. but when i upload it to my shared server. it just doesn't work. the code is below. bmpOut = new Bitmap(Size, Size); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, Size, Size); int topBottomPadding = 0; int leftRightPadding = 0; if (Size > lnNewWidth + 1) leftRightPadding = Convert.ToInt32((Size - lnNewWidth) / 2); else if (Size > lnNewHeight + 1) topBottomPadding = Convert.ToInt32((Size - lnNewHeight) / 2); g.DrawImage(loBMP, leftRightPadding, topBottomPadding, lnNewWidth, lnNewHeight); Bitmap bmp = new Bitmap(bmpOut); if (bmp != null) bmp.Save(ResizedOutput); bmp.Dispose(); bmpOut.Dispose(); g.Dispose(); loBMP.Dispose(); stack trace: [ExternalException (0x80004005): A generic error occurred in GDI+.] System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630 System.Drawing.Image.Save(String filename, ImageFormat format) +69 System.Drawing.Image.Save(String filename) +25 Utilities.ResizeImage(String fileName, String mode) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Utilities.cs:181 Link.ToProductImage(String fileName) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Link.cs:79 Product.PopulateControls(ProductDetails pd) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:37 Product.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:20

    Read the article

  • Bilinear interpolation - DirectX vs. GDI+

    - by holtavolt
    I have a C# app for which I've written GDI+ code that uses Bitmap/TextureBrush rendering to present 2D images, which can have various image processing functions applied. This code is a new path in an application that mimics existing DX9 code, and they share a common library to perform all vector and matrix (e.g. ViewToWorld/WorldToView) operations. My test bed consists of DX9 output images that I compare against the output of the new GDI+ code. A simple test case that renders to a viewport that matches the Bitmap dimensions (i.e. no zoom or pan) does match pixel-perfect (no binary diff) - but as soon as the image is zoomed up (magnified), I get very minor differences in 5-10% of the pixels. The magnitude of the difference is 1 (occasionally 2)/256. I suspect this is due to interpolation differences. Question: For a DX9 ortho projection (and identity world space), with a camera perpendicular and centered on a textured quad, is it reasonable to expect DirectX.Direct3D.TextureFilter.Linear to generate identical output to a GDI+ TextureBrush filled rectangle/polygon when using the System.Drawing.Drawing2D.InterpolationMode.Bilinear setting? For this (magnification) case, the DX9 code is using this (MinFilter,MipFilter set similarly): Device.SetSamplerState(0, SamplerStageStates.MagFilter, (int)TextureFilter.Linear); and the GDI+ path is using: g.InterpolationMode = InterpolationMode.Bilinear; I thought that "Bilinear Interpolation" was a fairly specific filter definition, but then I noticed that there is another option in GDI+ for "HighQualityBilinear" (which I've tried, with no difference - which makes sense given the description of "added prefiltering for shrinking") Followup Question: Is it reasonable to expect pixel-perfect output matching between DirectX and GDI+ (assuming all external coordinates passed in are equal)? If not, why not? Finally, there are a number of other APIs I could be using (Direct2D, WPF, GDI, etc.) - and this question generally applies to comparing the output of "equivalent" bilinear interpolated output images across any two of these. Thanks!

    Read the article

  • Is there bug in the Matrix.RotateAt method for certain angles? .Net Winforms

    - by Jules
    Here's the code i'm using to rotate: Dim m As New System.Drawing.Drawing2D.Matrix Dim size = image.Size m.RotateAt(degreeAngle, New PointF(CSng(size.Width / 2), CSng(size.Height / 2))) Dim temp As New Bitmap(600, 600, Imaging.PixelFormat.Format32bppPArgb) Dim g As Graphics = Graphics.FromImage(temp) g.Transform = m g.DrawImage(image, 0, 0) (1) Disposals removed for brevity. (2) I test the code with a 200 x 200 rectangle. (3) Size 600,600 it just an arbitrary large value that I know will fit the right and bottom sides of the rotated image for testing purposes. (4) I know, with this code, the top and left edges will be clipped because I'm not transforming the orgin after the rotate. The problem only occurs at certain angles: (1) At 90, the right hand edge disappears completely. (2) At 180, the right and bottom edges are there, but very faded. (3) At 270, the bottom edge disappears completely. Is this a known bug? If I manually rotate the corners an draw the image by specifying an output rectangle, I don't get the same problem - though it is slightly slower than using RotateAt.

    Read the article

  • Moving a high quality line on a panel c#

    - by user1787601
    I want to draw a line on a panel and then move it as the mouse moves. To do so, I draw the line and when the mouse moves I redraw the line to the new location and remove the previous line by drawing a line with the background color on it. It works fine if I do not use the high quality smoothing mode. But if use high quality smoothing mode, it leave traces on the panel. Does anybody know how to fix this? Thank you. Here is the code int x_previous = 0; int y_previous = 0; private void panel1_MouseMove(object sender, MouseEventArgs e) { Pen pen1 = new System.Drawing.Pen(Color.Black, 3); Pen pen2 = new System.Drawing.Pen(panel1.BackColor, 3); Graphics g = panel1.CreateGraphics(); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.DrawLine(pen2, new Point(0, 0), new Point(x_previous, y_previous)); g.DrawLine(pen1, new Point(0, 0), new Point(e.Location.X, e.Location.Y)); x_previous = e.Location.X; y_previous = e.Location.Y; } Here is the snapshot with SmoothingMode Here is the snapshot without SmoothingMode

    Read the article

  • Cant full read querystring data in mvc4 application using a class array as input to action

    - by Anders Lindén
    I have made a mvc4 application and I have a Controller that outputs a png file like this: using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; using System.Web.Mvc; using Foobar.Classes; namespace Foobar.Controllers { public class ImageController : Controller { public ActionResult Index(Label[] labels) { var bmp = new Bitmap(400, 300); var pen = new Pen(Color.Black); var font = new Font("arial", 20); var g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; if (labels != null) { g.DrawString("" + labels.Length, font, pen.Brush, 20, 20); if (labels.Length > 0) { g.DrawString("" + labels[0].label, font, pen.Brush, 20, 40); } } var stream = new MemoryStream(); bmp.Save(stream, ImageFormat.Png); stream.Position = 0; return File(stream, "image/png"); } } } The Label class looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Foobar.Classes { public class Label { public string label { get; set; } public int fontsize { get; set; } } } When I run my controller having this in the url: http://localhost:57775/image?labels[0][label]=Text+rad+1&labels[0][fontsize]=5&labels[1][fontsize]=5&labels[2][fontsize]=5 I get the correct amount of labels, so the image will show 3. But the instances of Label will not get its data members fill in. I have also tried to do this using plain variables (not properties). If they were filled in, the image would actually show "3" and "Text rad 1". So what do I put in the class "Label" to have the properties right? Should there be some kind of annotation? Where do I read about this?

    Read the article

  • Error:A generic error occurred in GDI+

    - by sanfra1983
    Hi, I created a web project on the server, and when I upload an image shows me the error Error: A generic error occurred in GDI +. I have read many links on the net that talk about this issue, and although I made the changes, nothing went wrong. I was thinking if the case is not an issue of permissions to folders. In fact I have two folders one inside the other. This is the code to resize the image: public Bitmaps ResizeImage (Stream stream, int? width, int? height) ( System.Drawing.Bitmap bmpOut = null; const int defaultWidth = 800; const int defaultHeight = 600; int width = lnWidth == null? defaultWidth: (int) width; int height = lnHeight == null? defaultHeight: (int) height; try ( LoBMP bitmap = new Bitmap (stream); ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; lnNewWidth int = 0; lnNewHeight int = 0; if (loBMP.Width <& & lnWidth loBMP.Height <lnHeight) ( loBMP return; ) if (loBMP.Width> loBMP.Height) ( lnRatio = (decimal) lnWidth / loBMP.Width; lnNewWidth = lnWidth; decimal = lnTemp loBMP.Height lnRatio *; lnNewHeight = (int) lnTemp; ) else ( lnRatio = (decimal) lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal = lnTemp loBMP.Width lnRatio *; lnNewWidth = (int) lnTemp; ) bmpOut = new Bitmap (lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage (bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle (Brushes.White, 0, 0, lnNewWidth, lnNewHeight); g.DrawImage (loBMP, 0, 0, lnNewWidth, lnNewHeight); loBMP.Dispose (); ) catch ( return null; ) bmpOut return; ) and this is the code that I insert in the codebehind: string filepath = AppDomain.CurrentDomain.BaseDirectory + img_veterinario / "; string = filepathM AppDomain.CurrentDomain.BaseDirectory + img_veterinario / img_veterinarioM; Reseize Reseize R = new (); Bitmap = photosFileOriginal r.ResizeImage (fucasiclinici.PostedFile.InputStream, 400, 400); Bitmap = photosFileMiniatura r.ResizeImage (fucasiclinici.PostedFile.InputStream, 72, 72); String filename = Path.GetFileName (fucasiclinici.PostedFile.FileName); photosFileOriginal.Save (Path.Combine (filepath, filename)); photosFileMiniatura.Save (Path.Combine (filepathM, filename)); Can you help me? Thanks

    Read the article

  • error CS0177: The out parameter 'Wx' must be assigned to before control leaves the current method

    - by sonny5
    using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class Form1 : System.Windows.Forms.Form { public static float WXmin; public static float WYmin; public static float WXmax; public static float WYmax; public static int VXmin; public static int VYmin; public static int VXmax; public static int VYmax; public static float Vx; public static float Vy; public Form1() { InitializeComponent(); } private void InitializeComponent() { //this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 300); this.Text="Pass Args"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.doLine); } static void Main() { Application.Run(new Form1()); } private void doLine(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); Pen p = new Pen(Color.Black); g.DrawLine(p, 0, 0, 100, 100); p.Dispose(); } private void eachCornerPix (object sender, PaintEventArgs e, out float Wx, out float Wy, out float Vx, out float Vy) { Graphics g = this.CreateGraphics(); Pen penBlu = new Pen(Color.Blue, 2); SolidBrush redBrush = new SolidBrush(Color.Red); int width = 2; // 1 pixel wide in x int height = 2; float [] Wxc = {0.100f, 5.900f, 5.900f, 0.100f}; float [] Wyc = {0.100f, 0.100f, 3.900f, 3.900f}; for (int i = 0; i<3; i++) { Wx = Wxc[i]; Wy = Wyc[i]; Vx = ((Wx - WXmin)*((VXmax-VXmin)+VXmin)/(WXmax-WXmin)); Vy = ((Wy - WYmin)*(VYmax-VYmin)/(WYmax-WYmin)+VYmin); Console.WriteLine("eachCornerPix Vx= {0}", Vx); Console.WriteLine("eachCornerPix Vy= {0}", Vy); g.FillRectangle(redBrush, Vx, Vy, width, height); g.Dispose(); } // Desired effect: Use the array values (Wxc, Wyc) and re-assign them to Wx and Wy. Then use // Wx and Wy as components to calculate Vx and Vy. // My end goal...once compile issues are resolved, is to pass each array value listed // using this method. This should allow 4 xy point pairs to be plotted. // Errors: // pass1.cs(51,18): error CS0177: The out parameter 'Wx' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Wy' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Vx' must be assigned to before // control leaves the current method // pass1.cs(51,18): error CS0177: The out parameter 'Vy' must be assigned to before // control leaves the current method } }

    Read the article

  • Why a graphics overflow problem as a result of a for loop?

    - by sonny5
    using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Drawing.Imaging; using System.Drawing.Drawing2D; public class Form1 : System.Windows.Forms.Form { public static float WXmin; public static float WYmin; public static float WXmax; public static float WYmax; public static int VXmin; public static int VYmin; public static int VXmax; public static int VYmax; public static float Wx; public static float Wy; public static float Vx; public static float Vy; public Form1() { InitializeComponent(); } private void InitializeComponent() { this.ClientSize = new System.Drawing.Size(400, 300); this.Text="Pass Args"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.doLine); //this.Paint += new System.PaintEventHandler(this.eachCornerPix); //eachCornerPix(out Wx, out Wy, out Vx, out Vy); } static void Main() { Application.Run(new Form1()); } private void doLine(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, this.ClientRectangle); Pen p = new Pen(Color.Black); g.DrawLine(p, 0, 0, 100, 100); // draw DOWN in y, which is positive since no matrix called eachCornerPix(sender, e, out Wx, out Wy, out Vx, out Vy); p.Dispose(); } private void eachCornerPix (object sender, System.EventArgs e, out float Wx, out float Wy, out float Vx, out float Vy) { Wx = 0.0f; Wy = 0.0f; Vx = 0.0f; Vy = 0.0f; Graphics g = this.CreateGraphics(); Pen penBlu = new Pen(Color.Blue, 2); SolidBrush redBrush = new SolidBrush(Color.Red); int width = 2; // 1 pixel wide in x int height = 2; float [] Wxc = {0.100f, 5.900f, 5.900f, 0.100f}; float [] Wyc = {0.100f, 0.100f, 3.900f, 3.900f}; Console.WriteLine("Wxc[0] = {0}", Wxc[0]); Console.WriteLine("Wyc[3] = {0}", Wyc[3]); /* for (int i = 0; i<3; i++) { Wx = Wxc[i]; Wy = Wyc[i]; Vx = ((Wx - WXmin)*((VXmax-VXmin)+VXmin)/(WXmax-WXmin)); Vy = ((Wy - WYmin)*(VYmax-VYmin)/(WYmax-WYmin)+VYmin); Console.WriteLine("eachCornerPix Vx= {0}", Vx); Console.WriteLine("eachCornerPix Vy= {0}", Vy); g.FillRectangle(redBrush, Vx, Vy, width, height); } */ // What is there about this for loop that will not run? // When the comments above and after the for loop are removed, it gets an overflow? g.Dispose(); } }

    Read the article

  • Please help me correct the small bugs in this image editor

    - by Alex
    Hi, I'm working on a website that will sell hand made jewelry and I'm finishing the image editor, but it's not behaving quite right. Basically, the user uploads an image which will be saved as a source and then it will be resized to fit the user's screen and saved as a temp. The user will then go to a screen that will allow them to crop the image and then save it to it's final versions. All of that works fine, except, the final versions have 3 bugs. First is some black horizontal line on the very bottom of the image. Second is an outline of sorts that follows the edges. I thought it was because I was reducing the quality, but even at 100% it still shows up... And lastly, I've noticed that the cropped image is always a couple of pixels lower than what I'm specifying... Anyway, I'm hoping someone whose got experience in editing images with C# can maybe take a look at the code and see where I might be going off the right path. Oh, by the way, this in an ASP.NET MVC application. Here's the code: using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; namespace Website.Models.Providers { public class ImageProvider { private readonly ProductProvider ProductProvider = null; private readonly EncoderParameters HighQualityEncoder = new EncoderParameters(); private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single( c => (c.MimeType == "image/jpeg")); private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products"); private readonly short[][] Dimensions = new short[3][] { new short[2] { 640, 480 }, new short[2] { 240, 0 }, new short[2] { 80, 60 } }; ////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////// ////////////////////////////////////////////////////////// public ImageProvider( ProductProvider ProductProvider) { this.ProductProvider = ProductProvider; HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L); } ////////////////////////////////////////////////////////// // Crop ////////////////////////////////////////////// ////////////////////////////////////////////////////////// public void Crop( string FileName, Image Image, Crop Crop) { using (Bitmap Source = new Bitmap(Image)) { using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) { using (Graphics Graphics = Graphics.FromImage(Target)) { Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; Graphics.SmoothingMode = SmoothingMode.HighQuality; Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; Graphics.CompositingQuality = CompositingQuality.HighQuality; Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel); }; Target.Save(FileName, JpegCodecInfo, HighQualityEncoder); }; }; } ////////////////////////////////////////////////////////// // Crop & Resize ////////////////////////////////////// ////////////////////////////////////////////////////////// public void CropAndResize( Product Product, Crop Crop) { using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) { using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) { float Percent = ((float)Source.Width / (float)Temp.Width); short Width = (short)(Temp.Width * Percent); short Height = (short)(Temp.Height * Percent); Crop.Height = (short)(Crop.Height * Percent); Crop.Left = (short)(Crop.Left * Percent); Crop.Top = (short)(Crop.Top * Percent); Crop.Width = (short)(Crop.Width * Percent); Img Img = new Img(); this.ProductProvider.AddImageAndSave(Product, Img); this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop); using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) { this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder); this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder); this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder); }; }; }; this.Purge(Product); } ////////////////////////////////////////////////////////// // Queue ////////////////////////////////////////////// ////////////////////////////////////////////////////////// public void QueueFor( Product Product, HttpPostedFileBase PostedFile) { using (Image Image = Image.FromStream(PostedFile.InputStream)) { this.Resize(new short[2] { 1152, 0 }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder); }; PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId)); } ////////////////////////////////////////////////////////// // Purge ////////////////////////////////////////////// ////////////////////////////////////////////////////////// private void Purge( Product Product) { string Source = String.Format("{0}/{1}.source", Path, Product.ProductId); string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId); if (File.Exists(Source)) { File.Delete(Source); }; if (File.Exists(Temp)) { File.Delete(Temp); }; foreach (Img Img in Product.Imgs) { string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId); if (File.Exists(Cropped)) { File.Delete(Cropped); }; }; } ////////////////////////////////////////////////////////// // Resize ////////////////////////////////////////////// ////////////////////////////////////////////////////////// public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) { if (Dimensions[1] == 0) { Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0])); }; using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) { using (Graphics Graphics = Graphics.FromImage(Bitmap)) { Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; Graphics.SmoothingMode = SmoothingMode.HighQuality; Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; Graphics.CompositingQuality = CompositingQuality.HighQuality; Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]); }; Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters); }; } } } Here's one of the images this produces:

    Read the article

  • Graphics.MeasureCharacterRanges giving wrong size calculations in C#.Net?

    - by Owen Blacker
    I'm trying to render some text into a specific part of an image in a Web Forms app. The text will be user entered, so I want to vary the font size to make sure it fits within the bounding box. I have code that was doing this fine on my proof-of-concept implementation, but I'm now trying it against the assets from the designer, which are larger, and I'm getting some odd results. I'm running the size calculation as follows: StringFormat fmt = new StringFormat(); fmt.Alignment = StringAlignment.Center; fmt.LineAlignment = StringAlignment.Near; fmt.FormatFlags = StringFormatFlags.NoClip; fmt.Trimming = StringTrimming.None; int size = __startingSize; Font font = __fonts.GetFontBySize(size); while (GetStringBounds(text, font, fmt).IsLargerThan(__textBoundingBox)) { context.Trace.Write("MyHandler.ProcessRequest", "Decrementing font size to " + size + ", as size is " + GetStringBounds(text, font, fmt).Size() + " and limit is " + __textBoundingBox.Size()); size--; if (size < __minimumSize) { break; } font = __fonts.GetFontBySize(size); } context.Trace.Write("MyHandler.ProcessRequest", "Writing " + text + " in " + font.FontFamily.Name + " at " + font.SizeInPoints + "pt, size is " + GetStringBounds(text, font, fmt).Size() + " and limit is " + __textBoundingBox.Size()); I then use the following line to render the text onto an image I'm pulling from the filesystem: g.DrawString(text, font, __brush, __textBoundingBox, fmt); where: __fonts is a PrivateFontCollection, PrivateFontCollection.GetFontBySize is an extension method that returns a FontFamily RectangleF __textBoundingBox = new RectangleF(150, 110, 212, 64); int __minimumSize = 8; int __startingSize = 48; Brush __brush = Brushes.White; int size starts out at 48 and decrements within that loop Graphics g has SmoothingMode.AntiAlias and TextRenderingHint.AntiAlias set context is a System.Web.HttpContext (this is an excerpt from the ProcessRequest method of an IHttpHandler) The other methods are: private static RectangleF GetStringBounds(string text, Font font, StringFormat fmt) { CharacterRange[] range = { new CharacterRange(0, text.Length) }; StringFormat myFormat = fmt.Clone() as StringFormat; myFormat.SetMeasurableCharacterRanges(range); using (Graphics g = Graphics.FromImage(new Bitmap( (int) __textBoundingBox.Width - 1, (int) __textBoundingBox.Height - 1))) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; Region[] regions = g.MeasureCharacterRanges(text, font, __textBoundingBox, myFormat); return regions[0].GetBounds(g); } } public static string Size(this RectangleF rect) { return rect.Width + "×" + rect.Height; } public static bool IsLargerThan(this RectangleF a, RectangleF b) { return (a.Width > b.Width) || (a.Height > b.Height); } Now I have two problems. Firstly, the text sometimes insists on wrapping by inserting a line-break within a word, when it should just fail to fit and cause the while loop to decrement again. I can't see why it is that Graphics.MeasureCharacterRanges thinks that this fits within the box when it shouldn't be word-wrapping within a word. This behaviour is exhibited irrespective of the character set used (I get it in Latin alphabet words, as well as other parts of the Unicode range, like Cyrillic, Greek, Georgian and Armenian). Is there some setting I should be using to force Graphics.MeasureCharacterRanges only to be word-wrapping at whitespace characters (or hyphens)? This first problem is the same as post 2499067. Secondly, in scaling up to the new image and font size, Graphics.MeasureCharacterRanges is giving me heights that are wildly off. The RectangleF I am drawing within corresponds to a visually apparent area of the image, so I can easily see when the text is being decremented more than is necessary. Yet when I pass it some text, the GetBounds call is giving me a height that is almost double what it's actually taking. Using trial and error to set the __minimumSize to force an exit from the while loop, I can see that 24pt text fits within the bounding box, yet Graphics.MeasureCharacterRanges is reporting that the height of that text, once rendered to the image, is 122px (when the bounding box is 64px tall and it fits within that box). Indeed, without forcing the matter, the while loop iterates to 18pt, at which point Graphics.MeasureCharacterRanges returns a value that fits. The trace log excerpt is as follows: Decrementing font size to 24, as size is 193×122 and limit is 212×64 Decrementing font size to 23, as size is 191×117 and limit is 212×64 Decrementing font size to 22, as size is 200×75 and limit is 212×64 Decrementing font size to 21, as size is 192×71 and limit is 212×64 Decrementing font size to 20, as size is 198×68 and limit is 212×64 Decrementing font size to 19, as size is 185×65 and limit is 212×64 Writing VENNEGOOR of HESSELINK in DIN-Black at 18pt, size is 178×61 and limit is 212×64 So why is Graphics.MeasureCharacterRanges giving me a wrong result? I could understand it being, say, the line height of the font if the loop stopped around 21pt (which would visually fit, if I screenshot the results and measure it in Paint.Net), but it's going far further than it should be doing because, frankly, it's returning the wrong damn results. Any and all help gratefully received. Thanks!

    Read the article

1 2  | Next Page >