Quantcast
Channel: System.Drawing/GDI+
Viewing all 176 articles
Browse latest View live

calculate the pixels of an image

$
0
0

I want to prompt the user to upload an image of specified size(in kb) and dimensions(in pixels). I managed to calculate the size of the uploaded image,for example limit the size of the image to 40 kb

file.ContentLength<40*1024

now I want to get the size of file as well say for example limit its sizes to not more than 320x50 px

I have searched for dimension of images and all i found is how to upload images or how to make a gallery but nothing about dimensions.

how can I calculate the pixels using mvc 5?


Image cropping and resize

$
0
0

I have a system here to upload an image and crop it using asp.net. When I save the cropped image, It won't resize and stay as the original. 
How do I resize the picture? 

My code: 

	protected void btnCrop_Click(object sender, EventArgs e)
	{
		if (hdnW.Value != "")
		{
			string sImagePathImages = Server.MapPath("images/");
			m_sImageNameUserUpload = Session["ImageName"].ToString();
			// Get Width, Height, X & Y coordinates from hidden field which gets value when you select an area to crop.
			int iWidth = Convert.ToInt32(hdnW.Value);
			int iHeight = Convert.ToInt32(hdnH.Value);
			int iXCoord = Convert.ToInt32(hdnX.Value);
			int iYCoord = Convert.ToInt32(hdnY.Value);
			//Call CropImage method defined below
			byte[] byt_CropImage = cropImage(sImagePathImages + m_sImageNameUserUpload, iWidth, iHeight, iXCoord, iYCoord);
			using (MemoryStream oMemoryStream = new MemoryStream(byt_CropImage, 0, byt_CropImage.Length))
			{
				oMemoryStream.Write(byt_CropImage, 0, byt_CropImage.Length);
				using (System.Drawing.Image oCroppedImage = System.Drawing.Image.FromStream(oMemoryStream, true))
				{
					string sSaveTo = sImagePathImages + m_sImageNameUserUpload;
					oCroppedImage.Save(sSaveTo, oCroppedImage.RawFormat);
				}
			}

			pnlUpload.Visible = false;
			pnlCrop.Visible = false;
			pnlCroppedImage.Visible = true;
			Response.Redirect("Welcome.aspx");
		}
		else
		{
			ltrMsg.Text = "<font color='red'><b>Please select area to crop.</b></font>";
		}
	}

	static byte[] cropImage(string sImagePath, int iWidth, int iHeight, int iX, int iY)
	{
		try
		{
			using (System.Drawing.Image oOriginalImage = System.Drawing.Image.FromFile(sImagePath))
			{
				using (System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(iWidth, iHeight))
				{
					oBitmap.SetResolution(oOriginalImage.HorizontalResolution, oOriginalImage.VerticalResolution);
					using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(oBitmap))
					{
						Graphic.SmoothingMode = SmoothingMode.AntiAlias;
						Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
						Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
						Graphic.DrawImage(oOriginalImage, new System.Drawing.Rectangle(0, 0, iWidth, iHeight), iX, iY, iWidth, iHeight, System.Drawing.GraphicsUnit.Pixel);
						MemoryStream oMemoryStream = new MemoryStream();
						oBitmap.Save(oMemoryStream, oOriginalImage.RawFormat);
						return oMemoryStream.GetBuffer();
					}
				}
			}
		}
		catch (Exception Ex)
		{
			throw (Ex);
		}
	}



Edit: Resizing works on chrome and mozila not on IE. Any idea why?

Best way to get the most crisp image for iPad Retina

$
0
0

Hi

I want to dynamically create a 300x300 png image (certificate) with various text items written using DrawString on it as well as a few smaller pngs placed on it.

Then I want to use that that image in a web page.

I have been experimenting with the code below.

Can anyone tell me what are the best settings to take advantage of iPad Retina displays (as well as newer iPhones, Samsungs etc) but also display OK on desktops and older phones?

For example, should I use SetResolution or should I create a 600x600 image and display that as <img width=300 height=300 etc>

Here's a demo: http://qviewer.com/test/s/default.aspx

I don't know however whether the text written on that blue image square is as crisp as how my iPad Retina displays text natively itself though.

Any thoughts/comments appreciated.

TIA
Mark

Imports Microsoft.VisualBasic
Imports System.Drawing
Imports System.Drawing.Drawing2D

Public Class cVVendorCertificateImageCreate

#Region "Dims"

    Dim imgClsCertificate As Bitmap
    Dim gClsGraphics1 As Graphics

    Dim fntArialBold14 As New Font("Arial", 14, FontStyle.Regular)
    Dim fntArialBold42 As New Font("Arial", 42, FontStyle.Regular)

#End Region

#Region "Functions"

    Public Function fCreateImage() As Boolean

        fCreateBase()
        fCreateItem1()
        fCreateItem2()

        'Save to file
        imgClsCertificate.Save("C:\Temp\011.png", System.Drawing.Imaging.ImageFormat.Png)

    End Function

    Private Function fCreateBase() As Boolean

        'Get blank white background png
        Dim strFrameBackgroundFileName As String = HttpContext.Current.Server.MapPath("~/pages/files/image-templates/Certificate/Certificate-background-white.png")
        imgClsCertificate = DirectCast(Image.FromFile(strFrameBackgroundFileName), Bitmap)

        'imgClsCertificate.SetResolution(264, 264)

        gClsGraphics1 = Graphics.FromImage(imgClsCertificate)

        With gClsGraphics1
            .SmoothingMode = SmoothingMode.HighQuality
            .TextRenderingHint = Text.TextRenderingHint.ClearTypeGridFit
            .CompositingQuality = CompositingQuality.HighQuality
        End With

    End Function

    Private Function fCreateItem1() As Boolean

        gClsGraphics1.DrawString("Hello how are you?", fntArialBold14, Brushes.Black, New PointF(50, 90))

    End Function


    Private Function fCreateItem2() As Boolean

        Dim strAddImage As String = HttpContext.Current.Server.MapPath("~/pages/files/image-templates/Certificate/image001.png")
        Dim imgFrame As Bitmap = DirectCast(Image.FromFile(strAddImage), Bitmap)
        gClsGraphics1.DrawImage(imgFrame,200, 200)

    End Function

#End Region

Gdi32 returns Arithmetic errors on Asp.Net

$
0
0

http://www.pinvoke.net/default.aspx/gdi32/GetFontData.html

following the guidance on https://msdn.microsoft.com/en-us/library/dd144885(v=vs.85).aspx 

"Minimum supported server Windows 2000 Server [desktop apps only]"

So how am I going to retrieve an embedded Font, say 'Verdana' from the GDI private font collection?

This is not working on Azure hosted Asp.Net site, on my local PC the byteCount is logical and correct (240456) but the uInt returned from code hosted on Asp.net is out of range (322122506) for byte array.

 

System.Drawing.Font gdiFont = font;IntPtr hfont = gdiFont.ToHfont();//System.DrawingIntPtr hdc = NativeMethods.GetDC(IntPtr.Zero);//user32.dllIntPtr oldFont = NativeMethods.SelectObject(hdc, hfont);//gdi32.dlluint byteCount = NativeMethods.GetFontData(hdc, nameTableKey, 0, fontData, 0);//gdi32.dll

Graphics.DrawString versus TextRenderer.DrawText?

$
0
0

Hi

I have many 300 x 300 plain (blank) light-blue pngs that I want to programatically draw various text on to then display on webpages.

What method (Graphics.DrawStringversusTextRenderer.DrawText) will give me the absolute clearest/crisp text (e.g. when using black/navy Arial 14px)?

And of the best method, what specific settings/flags would I use to get the clearest/crisp text (.net code sample would be helpful)?

The blank image will be fetched, drawn on then saved again in a batch process every hour so performance is not as important as trying to get the highest possible quality, especially since the majority of users may be viewing on retina iPhones or iPads.

TIA
Mark

Mapping a tiff over a gif with audio

$
0
0

Ok this may not be possible in ASP but what I have is a TIFF which is mostly transparent in the middle and a GIF which is several Jpegs and an MP4 video with music. I want to map the TIFF over the video and run the GIF right before and after the video in the same resolution.

How to generate a relational diagram??

$
0
0

Hi,everybody 

Recently I have to research a approach about generating some kind of a relational diagram from a recursive table,

and to display the diagram on web page.

Here is a URL of Image about the relational diagram should look like~

http://valkyria.wikia.com/wiki/File:Character_relationship_diagram.png

Who can tell me something like third party library or good idea to achieve my subject above??

ps.The framework of my application is asp.net or silverlight.

Thank all you~~

Change graphtype/chart run-time

$
0
0

Hi Friends,

Please I am  using following coding I am building runtime chart, my question I want to change the graphtype  like bar,pie, line  runtime, please help me how I can achieve this. thank you.

 

Me.Controls.Add(Chart1)

ChartArea1.Name = "ChartArea1"
Chart1.ChartAreas.Add(ChartArea1)
Legend1.Name = "Legend1"
Chart1.Legends.Add(Legend1)
Chart1.Location = New System.Drawing.Point(200, 40)
Series1.ChartArea = "ChartArea1"
Series1.Legend = "Legend1"
Series1.Name = "Missingindexes"
Chart1.Series.Add(Series1)
Chart1.Size = New System.Drawing.Size(800, 400)
Chart1.ChartAreas(0).AxisX.Title = "Tables Name"
Chart1.ChartAreas(0).AxisY.Title = "index_advantage"
Chart1.ChartAreas("ChartArea1").AxisX.IsLabelAutoFit = True
Chart1.ChartAreas("ChartArea1").AxisX.Interval = 1
' Chart1.ChartAreas("ChartArea1").AxisY.IsLabelAutoFit = True
Chart1.ChartAreas(0).AxisY.ScaleView.Zoomable = True

Chart1.ChartAreas(0).AxisX.Interval = 1
Chart1.ChartAreas(0).AxisY.IntervalOffset = 3

Chart1.Series("Missingindexes").ChartType = SeriesChartType.Line

Chart1.Series("Missingindexes").XValueMember = "Database.schema.table"
Chart1.Series("Missingindexes").YValueMembers = "index_advantage"

Chart1.DataSource = dt_table


A generic error occurred in GDI+

$
0
0

I am getting the above error trying to resize a file during upload.  Below is my code and I think it is failing during the Save method.

    Protected Sub BtnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnUpload.Click
        If FileUpload1.HasFile Then
            Dim img As String = String.Empty
            Dim bmpImg As Bitmap = Nothing
            Try
                bmpImg = FilesClass.Resize_Image(FileUpload1.PostedFile.InputStream, 640, 480)
                'change below to point to desired image location               
                img = Server.MapPath(txtImagePath.Text) & FileUpload1.FileName
                bmpImg.Save(img, ImageFormat.Jpeg)

                txtMsg.Text = "File named " & img & " was successfully uploaded and resized to 640 x 480."

            Catch ex As Exception
                Response.Write("Error occured: " & ex.Message.ToString())

            Finally
                img = String.Empty
                bmpImg.Dispose()

            End Try

        End If
    End Sub

And below is the FilesClass code.

    Public Shared Function Resize_Image(ByVal streamImage As Stream, ByVal maxWidth As Integer, ByVal maxHeight As Integer) As Bitmap

        Dim originalImage As New Bitmap(streamImage)
        Dim newWidth As Integer = originalImage.Width
        Dim newHeight As Integer = originalImage.Height
        Dim aspectRatio As Double = CDbl(originalImage.Width) / CDbl(originalImage.Height)

        If aspectRatio <= 1 AndAlso originalImage.Width > maxWidth Then
            newWidth = maxWidth
            newHeight = CInt(Math.Round(newWidth / aspectRatio))
        ElseIf aspectRatio > 1 AndAlso originalImage.Height > maxHeight Then
            newHeight = maxHeight
            newWidth = CInt(Math.Round(newHeight * aspectRatio))
        End If

        Return New Bitmap(originalImage, newWidth, newHeight)

    End Function

image.save problem

$
0
0
 Public Function ResizeAndSave(ByVal ImagePath As String, ByVal SavePath As String, ByVal FileName As String,
                                  ByVal xWidth As Int32, ByVal yHeight As Int32) As Boolean
        Dim bm As Bitmap
        Dim x As Int32 = xWidth
        Dim y As Int32 = yHeight
        Dim width As Integer = Val(x)
        Dim height As Integer = Val(y)
        Dim thumb As New Bitmap(width, height)
        Dim g As Graphics = Graphics.FromImage(thumb)
        Try
            Using images As New Bitmap(ImagePath)
                Using ms As New MemoryStream()
                    images.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
                    bm = Image.FromStream(ms)
                    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                    g.DrawImage(bm, New Rectangle(0, 0, width, height), New Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel)
                    g.Dispose()
                    thumb.Save(Server.MapPath(SavePath) + FileName)
                    bm.Dispose()
                    thumb.Dispose()
                End Using
            End Using
        Catch ex As Exception
            Throw New Execption(ex.Message)
        End Try
        Return True
    End Function

It is working when I debugging in local.

But when I put it in the server, I get this error message"System.Exception: Parameter is not valid."
How to fix this issue?

GDI+ implicityly converting all grayscale PNG images to 32bpp ARGB

$
0
0
I am using the ATL:CImage class to decode png images.
But the images are getting converted to RGBA (4 byte per pixel) images when loaded.

ATL:CImage img;
img.Load((LPCTSTR)("test.png")); // 8bit grayscale

after a successful load the m_nBPP member is 32 (aka 4 byte) and the m_bHasAlphaChannel is true. But they sould be 8 and false.

Due to the implicit conversion we need to convert the RGBA back to 8BPP manually. I am processing more than 400 images. So this is a major slow down for the application.

On Visual Studio forum I read that this is an issue in the GDI+ as its implicityly converting all grayscale PNG images to 32bpp ARGB.

Please let me know if there is a work around for this.

Thanks

Convert JPG image to PNG

$
0
0

I try to convert a JPG image to a PNG image
But i got some errors.

This is the script i use.

Till the thumbnailImage its a JPG, after it in the mstream i like to convert it to a PNG so i've got a better quality.
but i got an error.

The code i use:

System.Drawing.Image thumbnailImage = dbImage.GetThumbnailImage(new_width, new_height, null, new System.IntPtr());
System.IO.MemoryStream mstream = new System.IO.MemoryStream(byteArray, 0, ConvertImageToByteArray(thumbnailImage, System.Drawing.Imaging.ImageFormat.Png).Length);
thumbnailImage.Save(mstream, System.Drawing.Imaging.ImageFormat.Png);

So if i use System.Drawing.Imaging.ImageFormat.JPEG its going well!
But the quality is to bad, so i try to use PNG.

The errors i get:

On the first row:

"Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."

On the second:

"{"A generic error occurred in GDI+."}"

 Also i tried:

system.Drawing.Image dbImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(byteArray));
dbImage.Save(dbImage, System.Drawing.Imaging.ImageFormat.Png);

But right here i need to use a path... , i dont like to save it first, should i use a memorystream ore something here?

Need help, web enabled image doodler

$
0
0

Hey folks, I'm in the process of developing a EMR (Electronic Medical Record) system and one of the key things it needs is an image editor but more like a doodle type of tool.  My requirement is it loads a base background with the chart, the doc or nurse does their notation on the canvas, and then save the image to the drive as a new file.  Does anyone have anything they can share that will help me do this?  Thanks!

GDI+ Generic Error, multple frame tiff, multiple image formats

$
0
0

This is a question I posted on stack exchange, but have not gotten any answers.  I posted it on a Windows Server forum and was referred here.  This is occurring on Windows Server 2008 R2 systems.

I have seen many issues involving the GDI+ Generic Error, but I have not seen this particular matter raised before. We are consistently getting the error, on Windows systems other than Windows 8, when attempting to read (System.Drawing.Image.SelectActiveFrame) a multiple-frame tiff that includes frames in mixed Photometric Interpretation formats. That is to say, the file includes both RGB color and min-is-white formats, with corresponding differences in the Bits/Sample and Samples/Pixel frame parameters. The error is consistently raising as soon as a frame is encountered with a format that is different from that of the first frame.

          // Convert File from .tiff to .PDF
    static void ConvertFile(string file, string pdffilename)
    {
      string localMessage = string.Empty;

        try
        {
            //if it's a PDF Just renamed it and continue
            if (file.ToLower().Contains(".pdf"))
            {
                File.Copy(file, pdffilename);
                return;
            }
            // If file exists return
            if (File.Exists(pdffilename)) { return; }

            using (var stream = new FileStream(pdffilename, FileMode.Create))
            {
              localMessage = "01";
                var document = new iTextSharp.text.Document();
                localMessage = "01";
                var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream);
                localMessage = "02";
                var bm = Bitmap.FromFile(file);
                localMessage = "03";
                var total = bm.GetFrameCount(FrameDimension.Page);
                localMessage = "04";
                document.Open();
                //iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                localMessage = "05";
                iTextSharp.text.Image img = null;
                for (var currentframe = 0; currentframe < total; ++currentframe)
                {
                  localMessage = "06=>" + currentframe.ToString();
                  bm.SelectActiveFrame(FrameDimension.Page, currentframe);
                  localMessage = "07=>" + currentframe.ToString();
                  img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Bmp);
                  localMessage = "08=>" + currentframe.ToString();
                  img.ScalePercent(72f / img.DpiX * 100);
                  localMessage = "09=>" + currentframe.ToString();
                  img.SetAbsolutePosition(0, 0);
                  localMessage = "10=>" + currentframe.ToString();
                  iTextSharp.text.Rectangle pageRect = new iTextSharp.text.Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);
                  localMessage = "11=>" + currentframe.ToString();
                  document.SetPageSize(pageRect);
                  localMessage = "12=>" + currentframe.ToString();
                  document.NewPage();
                  localMessage = "13=>" + currentframe.ToString();
                  document.Add(img);
                }
                localMessage = "14";
                bm.Dispose();
                localMessage = "15";
                document.Close();

                localMessage = "16";
                stream.Close();
            }
        }
        catch (Exception exception)
        {
          string msg = exception.Message + "\r\n" +"Coversion Error--\r\n" +"\tinput file name: " + file + "\r\n" +"\toutput file name: " + pdffilename + "\r\n" +"\tlocal message" + localMessage + "\r\n";
            Console.WriteLine(msg);
            SaveError(msg);
            throw;
        }
    }

The "local message" is always "06=>n", where n is the 0-based index of the frame that transitions to a new format.

The error occurs whether the transition is from black and white to color, or color to black and white.  The issue does not seem to occur on Windows 8 boxes, but we only have W8 developer PCs, not servers.  It is a production process and needs to be deployed on a server.

Does anyone know why this is happening or how to fix it?

How to compress images before saving to database using c# with asp.net ?

$
0
0

Dear All,

I have four fileupload controls for uploading images in database, but i want to compress these images before saving into database.

Please suggest me.

Thanks & Regards,

Neeraj


class watermark in asp.net

$
0
0

Hi all,

I read a article : http://www.aspsnippets.com/Articles/Create-Add-Watermark-Text-to-Images-Photo-in-ASPNet-using-C-and-VBNet.aspx

Now , i want to convert function upload into class in order to re-use other websites :

protected void Upload(object sender, EventArgs e)
{
    string watermarkText = "© ASPSnippets.com";
    //Get the file name.
    string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName) + ".png";
    //Read the File into a Bitmap.
    using (Bitmap bmp = new Bitmap(FileUpload1.PostedFile.InputStream, false))
    {
        using (Graphics grp = Graphics.FromImage(bmp))
        {
            //Set the Color of the Watermark text.
            Brush brush = new SolidBrush(Color.Red);
            //Set the Font and its size.
            Font font = new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel);
            //Determine the size of the Watermark text.
            SizeF textSize = new SizeF();
            textSize = grp.MeasureString(watermarkText, font);
            //Position the text and draw it on the image.
            Point position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 10)));
            grp.DrawString(watermarkText, font, brush, position);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                //Save the Watermarked image to the MemoryStream.
                bmp.Save(memoryStream, ImageFormat.Png);
                memoryStream.Position = 0;
                //Start file download.
                Response.Clear();
                Response.ContentType = "image/png";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                //Write the MemoryStream to the Response.
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.Close();
                Response.End();
            }
        }
    }
}

Anyone help me to do this. I did it but not cover all situations and find errors.
Thank you so much !

class watermark in asp.net - keeping image quality

$
0
0

Split off from http://forums.asp.net/t/2078285.aspx?class+watermark+in+asp+net

I did your guide and add more :

 grp.CompositingQuality = CompositingQuality.HighQuality;
 grp.SmoothingMode = SmoothingMode.HighQuality;
 grp.InterpolationMode = InterpolationMode.HighQualityBicubic;

But image quality is still not good ! in code of first thread , i dont see any code line to resize image !
Have you other solutions ?

Thank you so much !

How do I create an image with watermark

$
0
0
How do I create an image with watermark so that when clicked it will open picture folder in my computer and then upload image.

Graphing a Growth Chart

$
0
0

Hello everyone and thanks for your help in advance.  I am at the early stages of development of an application that charts a patient's growth using the standardized growth chart from the CDC/WHO.  An example may be found at http://www.cdc.gov/growthcharts/data/who/grchrt_boys_24hdcirc-l4w_rev90910.pdf.  I need to be able to generate this chart through some type of webservice.  Since I have not done any type of graphing before, I am confused as to how to map each point on this chart.  Do I need to recreate the x-y axis in order to have a know increment to move up or across?  Or how do I figure out the distance between each point between the x point?  I know these are basic questions, but need some guidance getting started.  Any help would be appreciated.

I get the error: with the error belowwith the attached code: Any help would be very much appreciated.

$
0
0

With the following code, I get the error: 'bool'; type in a using statement must be implicitly convertible to 'System.IDisposable'

private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath) {
            //
            //   This sub scales an image and saves it to a folder
            //
            System.Drawing.Image image__1;
            using (image__1 == System.Drawing.Image.FromStream(sourcePath)) {
	            // can given width of image as we want
	            dynamic newWidth = Convert.ToInt32(Parser.Dbl(image__1.Width) * scaleFactor);
	            // can given height of image as we want
	            dynamic newHeight = Convert.ToInt32(Parser.Dbl(image__1.Height) * scaleFactor);
	            dynamic thumbnailImg = new Bitmap(newWidth, newHeight);
	            dynamic thumbGraph = Graphics.FromImage(thumbnailImg);
	            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
	            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
	            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
	            dynamic imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
	            thumbGraph.DrawImage(image__1, imageRectangle);
	            thumbnailImg.Save(targetPath, image__1.RawFormat);
            }
        }

Viewing all 176 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>