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

Adding watermark into image won't work on the server but works perfectly on the local machine?

$
0
0

I need some help on figuring out what are the reasons why? or what I've been missing on this because I could hardly figure out why this works in my local machine and is not working on the server. I have a code in C# to print a watermark on the image and it works perfectly on my local machine but when I applied it into my web host server where I'm updating my site. It won't print any markings. Any thoughts about this? Here's my code below to help you more track what might be the reason why it won't work from the server.

string watermarkText = "© mywebsite.com";

//Read the File into a Bitmap.
using (Bitmap bmp = new Bitmap(file.InputStream, false))
{
    using (Graphics grp = Graphics.FromImage(bmp))
    {
        //Set the Color of the Watermark text.
        Brush brush = new SolidBrush(Color.White);

        //Set the Font and its size.
        Font font = new System.Drawing.Font("san-serif", 20, FontStyle.Italic, 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);

        firstfname = Path.GetFileName(file.FileName).ToString();
        newfname = ProdId + firstfname;

        bmp.Save(Path.Combine(Server.MapPath("~/ProductImages/"), newfname));
        con.Open();
        string sqlProductImagesTab = "INSERT INTO [ProdImagesTab]([ProductIdforImages],[ProductImages],[SellerEmail]) Values('" + ProdId + "','" + newfname.Replace("'", "''") + "','" + SellerEmail + "')";
        SqlCommand cmd3 = new SqlCommand(sqlProductImagesTab, con);
        cmd3.CommandType = CommandType.Text;

        cmd3.ExecuteNonQuery();
        cmd3.Dispose();
        con.Close();

    }
}

 


How to save Ajax BarChart (VS 2015 VB) as bitmap file?

$
0
0

Looking for how to save Ajax BarChart (Visual Studio 2015 VB.NET) as bitmap file (JPG or PNG...)... any ideas?

Writing text to a loaded image, and save it for printing with good quality

$
0
0

I need to create a certificate as an image, and the quality of printed out as A4 size is good, ideally the image too.

Specifically, I need to load an existing certificate template which contains a badge, a frame, and a signature (please see below regarding the best format of the template); then write text onto the loaded image, save it, and let user download it, and print it out.

My questions is about the quality of the image, especially when it is printed out.

1 Currently, the existing template is PDF file. What file format should I use, pdf vs image (.png, bmp, .jpg), so the print out quality is good?

2 If the template is image files, What must the dimension of the template, and DPI be for an A4 size print out.

3. Will using lines A, B and C below affect the print out quality?

This is an ASP.NET web forms project.

Below is the prototype:

static string imageBaseFilePath = @"D:\Dev\MyLab\ConsoleApplication1\CertificateGenerator\";
static string userName = "Stephen Jonathon";
static string testName = "Microsoft C# Deveoper Practice Test";
static string testDate = "Thursday, November 10, 2016";
static string score = "Score 33 / 33";
static void Main(string[] args)
{
string imageFilePath = imageBaseFilePath + "template.PNG"; //please question 1 above
Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);
const int dotsPerInch = 600; // define the quality in DPI
//http://stackoverflow.com/questions/11699219/save-an-image-as-a-bitmap-without-losing-quality
bitmap.SetResolution(dotsPerInch, dotsPerInch);
using (Graphics graphics = Graphics.FromImage(bitmap))
{

//graphics.SmoothingMode = SmoothingMode.AntiAlias; //line A
//graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //line B
//graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; //line C

graphics.DrawString(userName, new Font("Times-Roman", 0.1f, FontStyle.Regular, GraphicsUnit.Inch), Brushes.Black, 350f, 350f);
graphics.DrawString(testName, new Font("Times-Roman", 0.06f, FontStyle.Regular, GraphicsUnit.Inch), Brushes.Black, 180f, 420f);
graphics.DrawString(testDate, new Font("Times-Roman", 0.05f, FontStyle.Regular, GraphicsUnit.Inch), Brushes.Black, 350f, 490f);
graphics.DrawString(score, new Font("Times-Roman", 0.06f, FontStyle.Regular, GraphicsUnit.Inch), Brushes.Black, 350f, 550f);
}
string fileName = "result3600.PNG";
bitmap.Save(imageBaseFilePath + fileName);
}



Setting Bitmap.MakeTransparent(Color.Transparent) don't work after Graphics.DrawString

$
0
0

Hi guys,

       I want to add some word to a PNG, also I need other place without words transparent .

      The PNG I create by blow code

      

public string DrawPng(int w,int h,string imagePath)
        {
            Bitmap bitmap = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(bitmap);
            g.Save();
            g.Dispose();
            bitmap.MakeTransparent(Color.Transparent);
            string name = Guid.NewGuid().ToString().Replace("-","");
            bitmap.Save(imagePath+ name + ".png", ImageFormat.Png);
            return name + ".png";
        }

And I add the words with below

SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            grPhoto.DrawString(waterWords,         //string of text
                          crFont,                  //font
                          semiTransBrush,              //Brush
                          new PointF(xPosOfWm, yPosOfWm), //Position
                          StrFormat);

            bmPhoto.MakeTransparent(Color.Transparent);

As you have seen , I have set bmPhoto.MakeTransparent(Color.Transparent); but it doesn't work. I get the PNG with a black background.

Anyone helps?

thanks

Split and combine image

$
0
0

I'm trying to split the image using C# but it was unsuccessful, I need a master to guide me correct the below codes. thank you in advance! then how to code for combining the image after splitting the image 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace separateImg
{
	class Program
	{
		static void Main(string[] args)
		{
			Bitmap originalImage = new Bitmap(Image.FromFile(@"C:\Users\user pc\Downloads\Spiderman2.jpg"));
			Rectangle rect = new Rectangle(0, 0, originalImage.Width / 4, originalImage.Height);
			Bitmap firstHalf = originalImage.Clone(rect, originalImage.PixelFormat);
			firstHalf.Save(@"C:\Users\user pc\Downloads\Spider1.jpg");
			rect = new Rectangle((originalImage.Width / 4) * 2, 0, originalImage.Width / 4, originalImage.Height);
			Bitmap secondHalf = originalImage.Clone(rect, originalImage.PixelFormat);
			secondHalf.Save(@"C:\Users\user pc\Downloads\Spider2.jpg");
			rect = new Rectangle((originalImage.Width / 4) * 3, 0, originalImage.Width / 4, originalImage.Height);
			Bitmap thirdHalf = originalImage.Clone(rect, originalImage.PixelFormat);
			thirdHalf.Save(@"C:\Users\user pc\Downloads\Spider3.jpg");
			rect = new Rectangle((originalImage.Width / 4) * 4, 0, originalImage.Width / 4, originalImage.Height);
			Bitmap fourthHalf = originalImage.Clone(rect, originalImage.PixelFormat);
			fourthHalf.Save(@"C:\Users\user pc\Downloads\Spider4.jpg");
		}
	}
}

Color Depth in Image

$
0
0

HI there,

I have a program that converts scanned image files of given types into Tiff's so it can be processed by a 3rd party system.    The logic is: find files of types x,y,z, load into Image object in memory, save to tiff file. 

An interesting issue came up... when the background is coloured (e.g. a scan of pink or green coloured paper), the whole image is black.  I believe this is due to the color depth of my saved image not having sufficient colours to handle the shades of pink/green/etc. that the paper can (potentially) come in.  If I save the image with a straight forward Save command, it saves properly, just with a huge file size (e.g. no compression on the tiff was set):

img.Save(sfilename, System.Drawing.Imaging.ImageFormat.Tiff);
//img is a System.Drawing.Image object, sfilename is the given destination filename.

When I apply compression to the Image object and then save, is when the issue happens.  Wondering if anyone knows for sure what variable needs to be set in order to have it save compressed with the background color showing as the proper colour?

Problematic Class:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace TestImgConverter
{
    class ImageToTiffConverter
    {
        private ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/tiff");
        private EncoderParameters myEncoderParameters = new EncoderParameters(1);
        // Create an Encoder object based on the GUID

        // for the Compression parameter category.
        private System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Compression;



        private EncoderParameter myEncoderParameter;

        public ImageToTiffConverter()
        {

            myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionCCITT4);
            myEncoderParameters.Param[0] = myEncoderParameter;
        }




        public void SaveImageToTiff(Image img, string sfilename)
        {
            //img.Save(sfilename, System.Drawing.Imaging.ImageFormat.Tiff);
            img.Save(sfilename, myImageCodecInfo, myEncoderParameters);
        }




        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
    }
}

how to get notified when a printer runs out of paper using c#?

$
0
0

Hi All

I'm using the below code to print a document , so my question is how do i get notified when the printer runs out of paper or ink  using c#?

C# code

PrintDocument pd = new PrintDocument();

PrintController pc = new StandardPrintController();
pd.PrintController = pc;
pd.PrintPage += new PrintPageEventHandler(pqr);
pd.Print();

void pqr(object o, PrintPageEventArgs e)
{
var path1 = @"e:\abc.jpeg";
System.Drawing.Image i = System.Drawing.Image.FromFile(path1);
Point p = new Point(0, 0);
e.Graphics.DrawImage(i, p);
}

thanks in advance

Jeeva

Out of Memory Exception

$
0
0

Trying to display photos by paging through an array of objects with a path to the image. I want to re-dimension the photo on the fly based on the aspect ratio with CSS. I am using the Page_PreRender even and disabling the buttons so the user can't click before a session variable with an index can be initialized or the I get a null value error. I'm not instantiating the image and every click to the next button is a postback. I think it might be because I'm constantly bringing up images with every click. Here is the code...

protected void Page_PreRender(object sender, EventArgs e)
    {

        imgPhoto.ImageUrl = GetNextPhoto();
        string path = HttpContext.Current.Server.MapPath(imgPhoto.ImageUrl);
        int width = System.Drawing.Image.FromFile(path).Width;
        int height = System.Drawing.Image.FromFile(path).Height;
        if (width > height)
            imgPhoto.CssClass = "photoLandscape";
        else
            imgPhoto.CssClass = "photoPortrait";

        lbNext.Enabled = true;
        lbPrevious.Enabled = true;
    }


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

How to get image.Width and Height from an image NOT on the server ?

$
0
0

I found several threads to get Width & Height from an image which resides on a server / or localhost ...

but nowhere for an image not on my server ..

Any clue to get around ?

As for example  i need to get the Width and Heigt from this image ..

 http://i.colnect.net/images/o/372/970/372970.jpg

this BELOW works for images on a server as it uses Server.Mappath  and the Object written by Persists , which resides on my server ..

set Jpeg = Server.createObject("Persits.Jpeg")

Path = Server.Mappath("image.jpg")

' need something like :    Path = "http://i.colnect.net/images/o/372/970/372970.jpg"    but this does not work ...

set Jpeg = Server.createObject("Persits.Jpeg")

Path = Server.Mappath("image.jpg")

Jpeg.Open Path

Jpeg.Width = Jpeg.OriginalWidth

Jpeg.Height = Jpeg.OriginalHeight

response.write("W=" + Cstr( Jpeg.Width ) + "<br>")

response.write("H=" + Cstr( Jpeg.Height ) + "<br>")

KIS !!  Keep it simple ...

How do I create an algoritm

$
0
0

Hello!

Assume I have on the x-axes the display area from x=40 pixels to x=750
pixels because I have some text to the far left so the x -axis start at position x = 40
If I now want to set a lot of point in this coordinate system.
For example if I have x-value 0 this would be positioned  at x = 40 and
x-value 800 would be positioned at x=750.
So I have to transform my x value into the coordinate system where origo for
x is 40 and x max is 800.

I can't find a suitable algoritm that can transform my x values into this
coordinate system.

//Tony

Remove background color from Graphics.Clear()

$
0
0

HI all,

I have a code to resize image. it works good just one thing that I dont want. 

 Bitmap bmPhoto = new Bitmap(Width, Height,
                              PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(fullSizeImg.HorizontalResolution,
                             fullSizeImg.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.Red);
            grPhoto.InterpolationMode = InterpolationMode.Default;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;

            grPhoto.DrawImage(fullSizeImg,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();

In my bold section, it fills a Red color on outside of image. I dont want that red color. If I remove that line, it fills with black color. I dont want that color at all. I want it fits whatever empty spaces it is getting that filled with color.

how to create thumbnails while storing the image in images folder in webmatrix webpages razor site.

$
0
0

how to create thumbnails while storing the image in images folder in webmatrix webpages razor site.

A generic error occurred in GDI+

$
0
0

I'm trying to resize an image proportionally using the below code

 Image sourceimage = Image.FromStream(mainImg.InputStream);  //mainImg is of type HttpPostedFileBase
                        Guid g = Guid.NewGuid();
                        string fileName = g + "_" + System.IO.Path.GetFileName(mainImg.FileName);
Image thumbnail = TheGateMain.Helpers.ImageResize.resizeMyImage(sourceimage, new Size(525,328));


                        string thumbnailsPath = System.IO.Path.Combine(
                            Server.MapPath("~/Uploads/apartments/thumbnails"), fileName);
                        thumbnail.Save(thumbnailsPath);
//error is thrown here when saving the thumbnail

This is function of resizing the image

 public static Image resizeMyImage(Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }

please advice urgent

Thanks in advance

Open Type fonts in vb.net or C#

$
0
0
Hi I have been trying to use the open type fonts (.otf files) purchased from Adobe for one of our asp.net web applications. Even after i installed those fonts, Either installedfontcollection is not getting those fonts or using Privatefontcollection also i am not able to add those fonts. When i use addfontfile method, it says, file not found. Please advice.

draw on image using System.Drawing.Image

$
0
0

Hello everyone, I have this example from another post:

https://forums.asp.net/t/2148342.aspx?how+to+mark+on+image+

So this will draw this string on the image:

double() text = {1, 3,5, 6, 10, 15};

What happened now is that I am trying to get the scaling on the distance to display correctly. If my string is like this:

double() text = {1, 1.1, 1.2, 1.3. 1.4, 1.5};

Now the text displays one on top of the others. Is there a way I could use system.drawing.image and draw something like this

https://www.screencast.com/t/RXqb1EsmC

The image is just a sample of what I want to achieve. Please ignore all the writing in black. I just want the distances to spread out with lines pointing the location where they actually are one vertical line. 

Thanks

How do I create an algoritm

$
0
0

Hello!

Assume I have on the x-axes the display area from x=40 pixels to x=750
pixels because I have some text to the far left so the x -axis start at position x = 40
If I now want to set a lot of point in this coordinate system.
For example if I have x-value 0 this would be positioned  at x = 40 and
x-value 800 would be positioned at x=750.
So I have to transform my x value into the coordinate system where origo for
x is 40 and x max is 800.

I can't find a suitable algoritm that can transform my x values into this
coordinate system.

//Tony

Image File cutting/cropping custom scenario --

$
0
0

Hi.

I have a very unique scenario at hand and very honestly I am out of depth on how to do this.

In my app. I am generating png image files, with some content in it. The content keeps varying. That's not the main issue.
Well, What is --
My content dimensions are not exact fitting as the dimensions of the file. It is usually smaller, which leaves white/unused spaces in my generated image file.
WHAT I WOULD LIKE TO DO IS --
Have some mechanism that would calculate the size of the inside content height width and then crop/trip the remaining extra portion of the file, so that it's an exact fitting image.
Hope I am able to make you understand what I am trying to achieve here. Use this link to see: [https://imagebin.ca/v/4XPuDCzAAvGm]
What you see here is exactly my case. The inside content itself only occupies part of the total file. So the rest of it is white/empty. Which I want to do away with,and probably create a new file which is the exact fitting one.

How do I do this. Should I use some third party utility? Free? Or would I be required to bu any license.
How about using some core C# calculation logic like starting from the offset point and then doing some kind of calculation and cropping. How should I approach it. Can you at least provide me with some pseudo-code blocks or logical blocks that I may expand step by step and achieve my goal?

I really really really need it. Please steer me in the right direction. Any kind of suggestions and hints would be helpful for me at this  moment!!

Thanks in advance,
Protik

Scanned Image DPI is changed on using GDI+ API for saving image.

$
0
0

I am new to Twain and GDI+.

Application is developed using .Net.

Below GDI+ APIs used for image saving.

GdipCreateBitmapFromGdiDib(bminfo, pixdat, ref img);
GdipSaveImageToFile(img, picname, ref clsid, IntPtr.Zero);

Scanned image from Printer is saved as png using the TWAIN interface and GDI+ API.

Eventhough the imaged scanned from printer is 600 dpi/400 dpi/150dpi. After saving the image using GDI+ API the dpi is changed to 96 dpi.

Please let me know if you have any information why the dpi is changed.

Add whiteborder and text to Image

$
0
0

Hi guys.. I've nearly achieved my goal but got little improvement to my code.

1) How do I make that area to White Color as well?
* I knew that it's because I changed the following code from
totalCanvasSize.Height - (borderWidth * 2)
to 
totalCanvasSize.Height - (borderWidth * 4)


2) How can i show emoji image and text properly? and allow me to align text & image to left or center. (now is absolutely align to right)

Below is my existing code:

Code Behind

    Protected Sub btn_submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_submit.Click

        Dim path As String = MapPath(Context.Request.ApplicationPath & "/upload/JellyFish.jpg")
        Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(path)

        Dim imageWithWhiteBorder As System.Drawing.Image

        imageWithWhiteBorder = AppendBorder(System.Drawing.Image.FromFile(path), 20)
        imageWithWhiteBorder.Save("C:\JellyFish.jpg")


        Dim watermarkText As String = HttpUtility.HtmlDecode(Me.txt_richTextBox.Text)

        'Get the file name.
        Dim fileName As String = "JellyFishWithText.jpg"

        'Read the File into a Bitmap.
        Using bmp As New Bitmap("C:\JellyFish.jpg", False)
            Using grp As Graphics = Graphics.FromImage(bmp)

                'Set the Color of the Watermark text.
                Dim brush As Brush = New SolidBrush(Color.Black)

                'Set the Font and its size.
                Dim font As Font = New System.Drawing.Font("Arial", 20, FontStyle.Regular, GraphicsUnit.Pixel)

                'Determine the size of the Watermark text.
                Dim textSize As New SizeF()
                textSize = grp.MeasureString(watermarkText, font)

                'Position the text and draw it on the image.
                Dim position As New Point((bmp.Width - (CInt(textSize.Width) + 10)), (bmp.Height - (CInt(textSize.Height) + 10)))
                grp.DrawString(watermarkText, font, brush, position)

                Using memoryStream As 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", Convert.ToString("attachment; filename=") & fileName)

                    'Write the MemoryStream to the Response.
                    memoryStream.WriteTo(Response.OutputStream)
                    Response.Flush()
                    Response.Close()
                    Response.[End]()
                End Using
            End Using

        End Using

    End Sub
    Public Function AppendBorder(ByVal original As System.Drawing.Image, ByVal borderWidth As Integer) As System.Drawing.Image

        Dim borderColor As Color = Color.White
        Dim mypen As New Pen(borderColor, borderWidth * 2)
        Dim totalCanvasSize As New System.Drawing.Size(512, 512)

        Dim newImageRectWithoutBorder As New System.Drawing.Rectangle(borderWidth, borderWidth, totalCanvasSize.Width - (borderWidth * 2), totalCanvasSize.Height - (borderWidth * 6))

        Dim img As New System.Drawing.Bitmap(totalCanvasSize.Width, totalCanvasSize.Height)
        Dim g As Graphics = Graphics.FromImage(img)

        'g.Clear(borderColor)   
        g.DrawImage(original, newImageRectWithoutBorder)
        g.DrawRectangle(mypen, 0, 0, totalCanvasSize.Width, totalCanvasSize.Height)
        g.Dispose()

        Return img

    End Function
<form id="form1" runat="server"><div><script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script><script type="text/javascript">
        tinymce.init({
            selector: 'textarea',
            plugins: "emoticons",
            toolbar: "emoticons",
            width: 500
        });</script><asp:TextBox ID = "txt_richTextBox" runat="server" TextMode="MultiLine" /><asp:Button ID="btn_submit" runat="server" Text="Submit" /></div></form>






Viewing all 176 articles
Browse latest View live


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