none
A Graphics object cannot be created from an image that has an indexed pixel format. RRS feed

  • Question

  • I have this issue as mentioned in the title. and here is what I tried to do to solve it: This is MVC 5 project.

     [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index(string text, int text1)
            {                  
                DirectoryInfo dir = new DirectoryInfo(@"C:\Users\name\Desktop\images");
                FileInfo[] files = dir.GetFiles();
                string value = text;
                int value1 = text1;
                //string file = Path.GetFileNameWithoutExtension(postedFile.FileName) + ".png";
                foreach (FileInfo file in files)
                {
                    // string newfile = Path.GetFileNameWithoutExtension(file.FileName) + ".png";
                    //if (postedFile != null)
                    //{
                    // Load document
    
                    using (Bitmap bitmap = new Bitmap(file.FullName))
                    {
                        Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height);
                        using (Graphics graphics = Graphics.FromImage(tempBitmap))
                        {
                            graphics.DrawImage(bitmap, 0, 0);
                            // graphics.DrawLine();
                            Brush brush = new SolidBrush(Color.Black);
                            Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel);
                            SizeF textSize = new SizeF();
                            textSize = graphics.MeasureString(value, font);
                            Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10));
                            graphics.DrawString((value + value1++), font, brush, position);
                            using (MemoryStream mStream = new MemoryStream())
                            {
                                mStream.Position = 0;
                                tempBitmap.Save(mStream, ImageFormat.Tiff);
                                string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name);
                                tempBitmap.Save(_path);
    
                            }
                        }
                    }
    
    
    
                }
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                ViewBag.Message = ("RunTime " + watch.ElapsedMilliseconds);
                return View();
            }
            
    
        }

    This solve the error However the output images are extremely small. My question is: how do I make the output stay as same size. 

    Note: if I watermark/draw on .png file this method works fine its .tif that gives me the issue. I don't know how to convert all files to .png then edit it and then convert it back to .tif maybe that is one approach thank you. 


    • Edited by HelpIsNice Monday, January 6, 2020 9:20 PM
    Monday, January 6, 2020 9:19 PM

Answers

  • I have this issue as mentioned in the title. and here is what I tried to do to solve it: This is MVC 5 project.

     [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index(string text, int text1)
            {                  
                DirectoryInfo dir = new DirectoryInfo(@"C:\Users\name\Desktop\images");
                FileInfo[] files = dir.GetFiles();
                string value = text;
                int value1 = text1;
                //string file = Path.GetFileNameWithoutExtension(postedFile.FileName) + ".png";
                foreach (FileInfo file in files)
                {
                    // string newfile = Path.GetFileNameWithoutExtension(file.FileName) + ".png";
                    //if (postedFile != null)
                    //{
                    // Load document
    
                    using (Bitmap bitmap = new Bitmap(file.FullName))
                    {
                        Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height);
                        using (Graphics graphics = Graphics.FromImage(tempBitmap))
                        {
                            graphics.DrawImage(bitmap, 0, 0);
                            // graphics.DrawLine();
                            Brush brush = new SolidBrush(Color.Black);
                            Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel);
                            SizeF textSize = new SizeF();
                            textSize = graphics.MeasureString(value, font);
                            Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10));
                            graphics.DrawString((value + value1++), font, brush, position);
                            using (MemoryStream mStream = new MemoryStream())
                            {
                                mStream.Position = 0;
                                tempBitmap.Save(mStream, ImageFormat.Tiff);
                                string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name);
                                tempBitmap.Save(_path);
    
                            }
                        }
                    }
    
    
    
                }
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                ViewBag.Message = ("RunTime " + watch.ElapsedMilliseconds);
                return View();
            }
            
    
        }

    This solve the error However the output images are extremely small. My question is: how do I make the output stay as same size. 

    Note: if I watermark/draw on .png file this method works fine its .tif that gives me the issue. I don't know how to convert all files to .png then edit it and then convert it back to .tif maybe that is one approach thank you. 


    You need to specify the bitmap size apparently ie on this line add the bitmap size:

    graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
    otherwise the image size is too small when drawn there.

    • Marked as answer by HelpIsNice Tuesday, January 7, 2020 6:31 PM
    Monday, January 6, 2020 10:45 PM


  • [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(string text, int text1) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\syousif\Desktop\images"); FileInfo[] files = dir.GetFiles(); string value = text; int value1 = text1; foreach (FileInfo file in files) { using (Bitmap bitmap = new Bitmap(file.FullName)) { Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height); using (Graphics graphics = Graphics.FromImage(tempBitmap)) { graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); Brush brush = new SolidBrush(Color.Black); Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel); SizeF textSize = new SizeF(); textSize = graphics.MeasureString(value, font); Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10)); graphics.DrawString((value + value1++), font, brush, position); using (MemoryStream mStream = new MemoryStream()) { mStream.Position = 0; tempBitmap.Save(mStream, ImageFormat.Tiff); string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name); tempBitmap.Save(_path); } } }


    This is what I have now. The image comes out with the right zoom level and size. However the text that I/user insert that gets printed on it becomes externally small (you can barely see it)


    That is easy.   :)

    https://docs.microsoft.com/en-us/dotnet/api/system.drawing.font.-ctor?view=netframework-4.8#System_Drawing_Font__ctor_System_Drawing_FontFamily_System_Single_System_Drawing_FontStyle_

    Your font height of 10 is too small then? ie not big enough. Plus your units you specified are pixels.

    Oh I see its the units that are tricky?

    Make that number larger like 20 or 100 even. Try it see what happens.

    It is just like Word etc. but you are setting the height as pixels in your statement. Try the constructor where you dont need to set the units (default is points).

    If you use size in points then that is like Word uses and points are larger than pixels. ie 1 pnt = 1/72 inch. You computer monitor is probably 96 pixels per inch. Finally there is a user text scaling setting in the control panel the user can enlarge the windows text by 125, 150, 200 percent.

    It takes practice I guess. Play with it. You cant really break it.

     
    • Edited by tommytwotrain Tuesday, January 7, 2020 4:51 PM
    • Marked as answer by HelpIsNice Tuesday, January 7, 2020 6:31 PM
    Tuesday, January 7, 2020 4:50 PM

All replies

  • > However the output images are extremely small.

    What do you mean by that?  The output images necessary have the same number of pixels as the input images.  I assume if you zoom in, all of the pixels are there.

    Perhaps you just need to set the default resolution hint (Bitmap.SetResolution) on the output side.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, January 6, 2020 10:15 PM
  • I have this issue as mentioned in the title. and here is what I tried to do to solve it: This is MVC 5 project.

     [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index(string text, int text1)
            {                  
                DirectoryInfo dir = new DirectoryInfo(@"C:\Users\name\Desktop\images");
                FileInfo[] files = dir.GetFiles();
                string value = text;
                int value1 = text1;
                //string file = Path.GetFileNameWithoutExtension(postedFile.FileName) + ".png";
                foreach (FileInfo file in files)
                {
                    // string newfile = Path.GetFileNameWithoutExtension(file.FileName) + ".png";
                    //if (postedFile != null)
                    //{
                    // Load document
    
                    using (Bitmap bitmap = new Bitmap(file.FullName))
                    {
                        Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height);
                        using (Graphics graphics = Graphics.FromImage(tempBitmap))
                        {
                            graphics.DrawImage(bitmap, 0, 0);
                            // graphics.DrawLine();
                            Brush brush = new SolidBrush(Color.Black);
                            Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel);
                            SizeF textSize = new SizeF();
                            textSize = graphics.MeasureString(value, font);
                            Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10));
                            graphics.DrawString((value + value1++), font, brush, position);
                            using (MemoryStream mStream = new MemoryStream())
                            {
                                mStream.Position = 0;
                                tempBitmap.Save(mStream, ImageFormat.Tiff);
                                string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name);
                                tempBitmap.Save(_path);
    
                            }
                        }
                    }
    
    
    
                }
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                ViewBag.Message = ("RunTime " + watch.ElapsedMilliseconds);
                return View();
            }
            
    
        }

    This solve the error However the output images are extremely small. My question is: how do I make the output stay as same size. 

    Note: if I watermark/draw on .png file this method works fine its .tif that gives me the issue. I don't know how to convert all files to .png then edit it and then convert it back to .tif maybe that is one approach thank you. 


    You need to specify the bitmap size apparently ie on this line add the bitmap size:

    graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
    otherwise the image size is too small when drawn there.

    • Marked as answer by HelpIsNice Tuesday, January 7, 2020 6:31 PM
    Monday, January 6, 2020 10:45 PM
  • Hi HelpIsNice,

    Thank you for posting here.

    Is your current code just to upload all files from the local folder images to the UploadedFolders folder of the server?

    I don't know why you use Bitmap and Graphics to manipulate files. If your ultimate goal is to make the files in UploadedFolders and the files in images have the same size, then I suggest that you can use the CopyTo method directly, it can ensure that all file sizes are the same, and the .tif file looks the same as the original file.

    Here is the code :

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Index(string text, int text1)
            {       
               DirectoryInfo dir = new DirectoryInfo(@"C:\Users\name\Desktop\images");
               FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    string path = Server.MapPath("~/UploadedFolders/");
                    file.CopyTo(path + file.Name);
                }
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                ViewBag.Message = ("RunTime " + watch.ElapsedMilliseconds);
                return View();
            }
    
    

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, January 7, 2020 8:24 AM
  • Hi Timon thanks for your time. My goal is to get those images from a directory add page number to each one based on user input, and send the new images( with page number) to the new directory thats why I used Bitmap and Graphics to manipulate files.
    Tuesday, January 7, 2020 1:55 PM
  • This helps a lot but one issue still exist the text that is inserted is extremely small for the image that was tif originally here I have 2 results one was tif and one is png. The tif has that issue but the png doesn't. 


    Tuesday, January 7, 2020 2:48 PM
  • Timon,

    ie the discussion started here working with tif files:

    https://social.msdn.microsoft.com/Forums/en-US/edd45c87-366c-4af8-a6fe-8ba9b1ffb002/a-graphics-object-cannot-be-created-from-an-image-that-has-an-indexed-pixel-format?forum=csharpgeneral

    Nice is using the examaple from that thread modified as discussed along the way...

    That is the reason the original tifs are redrawn on a new bitmap. Then apparently more graphics are added now in this thread... etc.

    As I mentioned above the problem now is the size was not specified for the destination image in the original example and that made the tiff image draw smaller than we want. So the size of the destination image has been added in the drawimage statement to the example below.

    You can duplicate the size problem by uncommenting the drawimage statements in this example.

    No size in drawimage gives this size:

    Giving the size of the original tif in pixels gives this size image which is the original size:

    I think the tiff format resolution setting does that? The second reason we redraw the tif image.

     private void Form4_Load(object sender, EventArgs e)
            {
                Bitmap bitmap = new Bitmap(@"C:\bitmaps\drg mak cover front 600.tif");
    
                Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height);
    
                using (Graphics graphics = Graphics.FromImage(tempBitmap))
                {
                    //must specify the destination size as the size of the original or destination is small
                    graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
                    
                    //not specing the size causes the original image to draw at small size
                    //graphics.DrawImage(bitmap, 0, 0);
                }
    
                {
                    if (BackgroundImage != null)
                        BackgroundImage.Dispose();
                }
    
                this.BackgroundImage = tempBitmap;
                this.BackgroundImageLayout = ImageLayout.None;
    
                bitmap.Dispose();
            }

    Tuesday, January 7, 2020 2:53 PM


  • [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(string text, int text1) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\syousif\Desktop\images"); FileInfo[] files = dir.GetFiles(); string value = text; int value1 = text1; foreach (FileInfo file in files) { using (Bitmap bitmap = new Bitmap(file.FullName)) { Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height); using (Graphics graphics = Graphics.FromImage(tempBitmap)) { graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); Brush brush = new SolidBrush(Color.Black); Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel); SizeF textSize = new SizeF(); textSize = graphics.MeasureString(value, font); Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10)); graphics.DrawString((value + value1++), font, brush, position); using (MemoryStream mStream = new MemoryStream()) { mStream.Position = 0; tempBitmap.Save(mStream, ImageFormat.Tiff); string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name); tempBitmap.Save(_path); } } }


    This is what I have now. The image comes out with the right zoom level and size. However the text that I/user insert that gets printed on it becomes externally small (you can barely see it)


    • Edited by HelpIsNice Tuesday, January 7, 2020 3:19 PM
    Tuesday, January 7, 2020 3:14 PM


  • [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(string text, int text1) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\syousif\Desktop\images"); FileInfo[] files = dir.GetFiles(); string value = text; int value1 = text1; foreach (FileInfo file in files) { using (Bitmap bitmap = new Bitmap(file.FullName)) { Bitmap tempBitmap = new Bitmap(bitmap.Width, bitmap.Height); using (Graphics graphics = Graphics.FromImage(tempBitmap)) { graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height); Brush brush = new SolidBrush(Color.Black); Font font = new Font("Arial", 10, FontStyle.Italic, GraphicsUnit.Pixel); SizeF textSize = new SizeF(); textSize = graphics.MeasureString(value, font); Point position = new Point(bitmap.Width - ((int)textSize.Width + 30), bitmap.Height - ((int)textSize.Height + 10)); graphics.DrawString((value + value1++), font, brush, position); using (MemoryStream mStream = new MemoryStream()) { mStream.Position = 0; tempBitmap.Save(mStream, ImageFormat.Tiff); string _path = Path.Combine(Server.MapPath("~/UploadedFolders"), file.Name); tempBitmap.Save(_path); } } }


    This is what I have now. The image comes out with the right zoom level and size. However the text that I/user insert that gets printed on it becomes externally small (you can barely see it)


    That is easy.   :)

    https://docs.microsoft.com/en-us/dotnet/api/system.drawing.font.-ctor?view=netframework-4.8#System_Drawing_Font__ctor_System_Drawing_FontFamily_System_Single_System_Drawing_FontStyle_

    Your font height of 10 is too small then? ie not big enough. Plus your units you specified are pixels.

    Oh I see its the units that are tricky?

    Make that number larger like 20 or 100 even. Try it see what happens.

    It is just like Word etc. but you are setting the height as pixels in your statement. Try the constructor where you dont need to set the units (default is points).

    If you use size in points then that is like Word uses and points are larger than pixels. ie 1 pnt = 1/72 inch. You computer monitor is probably 96 pixels per inch. Finally there is a user text scaling setting in the control panel the user can enlarge the windows text by 125, 150, 200 percent.

    It takes practice I guess. Play with it. You cant really break it.

     
    • Edited by tommytwotrain Tuesday, January 7, 2020 4:51 PM
    • Marked as answer by HelpIsNice Tuesday, January 7, 2020 6:31 PM
    Tuesday, January 7, 2020 4:50 PM
  • I did change the font size to 50 that made it perfect on the .tif file but extremely large on the .png file my fear is: assume a folder contains both image types .tif and .png the png text watermark will come out large and tif image will come out with the right size and vise versa if I set font to 10. I guess is there a way to make it work on both with same font.

    Font font = new Font("Arial", 50, FontStyle.Italic, GraphicsUnit.Pixel);

    I might do an if else statement. If extension or contains .tif use a certain font else use 10 font

    something like that

    • Edited by HelpIsNice Tuesday, January 7, 2020 5:53 PM
    Tuesday, January 7, 2020 5:11 PM
  • I did change the font size to 50 that made it perfect on the .tif file but extremely large on the .png file my fear is: assume a folder contains both image types .tif and .png the png text watermark will come out large and tif image will come out with the right size and vise versa if I set font to 10. I guess is there a way to make it work on both with same font.

    Font font = new Font("Arial", 50, FontStyle.Italic, GraphicsUnit.Pixel);

    I might do an if else statement. If extension or contains .tif use a certain font else use 10 font

    something like that

    Hmm. You are losing me there.

    The files should be the same size image in pixels? That is why we set the size the same in the draw image. Font size should look drawn the same.

    PS It is not clear what you have from your example. Are you saving a png?

    Also I get some errors in the using bitmap of your example I am not sure why. That's why I removed it in my example. etc.

    In fact I am not sure about the memory stream you have setup there or what you mean to do with it?
    Tuesday, January 7, 2020 6:29 PM
  • Thank you for your time.

    MemoryStream was from old functionality I should have removed it.  "The files should be the same size image in pixels? That is why we set the size the same in the draw image. Font size should look drawn the same." I agree with this part unfortunately  this is not the case. if the input is .tif font 50 work good if the input is .png the font 10 works great. I also tried JPG as input and the output was unspeakable. By out put i meant image after editing. This is MVC project if that makes any difference.

    if I change this line tempBitmap.Save(mStream, ImageFormat.Tiff); To .png it doesn't change anything.

    I am thinking to either keep as is and add if else as I mentioned or use this library GraphicsMagic problem is there aren't many examples on how to use it 


    • Edited by HelpIsNice Tuesday, January 7, 2020 7:18 PM
    Tuesday, January 7, 2020 7:16 PM
  • Thank you for your time.

    MemoryStream was from old functionality I should have removed it.  "The files should be the same size image in pixels? That is why we set the size the same in the draw image. Font size should look drawn the same." I agree with this part unfortunately  this is not the case. if the input is .tif font 50 work good if the input is .png the font 10 works great. I also tried JPG as input and the output was unspeakable. By out put i meant image after editing. This is MVC project if that makes any difference.

    if I change this line tempBitmap.Save(mStream, ImageFormat.Tiff); To .png it doesn't change anything.

    I am thinking to either keep as is and add if else as I mentioned or use this library GraphicsMagic problem is there aren't many examples on how to use it 


    "I change this line tempBitmap.Save(mStream, ImageFormat.Tiff); To .png it doesn't change anything."

    What do you think that line does? I dont think it does anything as you have it? It saves the image in a memorystream reference which you never use??

    The next line of your code saves the image file. And it saves it with the name path + original filename.extension. Correct? The extension sets the format to what .tif? If the path has not changed you overwrite the original file? Else you save the file you drew on as new folder + filename.extension.

    What is it you want to do?

    You dont need GraphicsMagic. You just need to figure out what is wrong. What it is you dont understand or dont do right or etc. Its going you be something simple I will guess.

    Like I say I can't duplicate what you say your result is?

    Sleep on it. Ask the question again with a new write up. Pictures. Try to give a reproducible example. You will probably spot the problem making a new simple one file example. Leave out the folder loops. If not perhaps other forum members will see something with a new post, new name etc.


    Tuesday, January 7, 2020 9:03 PM