How to convert a Color tiff file to Black and white tiff file using vb/C# code?


Hi ,

   I have a lot of TIFF file in Color format. Now I want to convert into Black and White TIFF file because color is taking lot of memory.

 one color file is 5 MB.

How to convert a Color tiff file to Black and white tiff file using code?

 Please any one reply.

2/22/2009 8:19:25 AM 1803 articles. 0 followers. Follow

3 Replies

Similar Articles

[PageSpeed] 48

Here is the code you need !
use the ConvertToBitonal function to conver your color tiff file to black & white one.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;

namespace BitonalConverter
    public static class Converter
        public static Bitmap ConvertToRGB(Bitmap original)
            Bitmap newImage = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb);
            newImage.SetResolution(original.HorizontalResolution, original.VerticalResolution);
            Graphics g = Graphics.FromImage(newImage);
            g.DrawImageUnscaled(original,  0, 0);
            return newImage;

        public static Bitmap ConvertToBitonal(Bitmap original)
            Bitmap source = null;

            // If original bitmap is not already in 32 BPP, ARGB format, then convert
            if (original.PixelFormat != PixelFormat.Format32bppArgb)
                source = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb);
                source.SetResolution(original.HorizontalResolution, original.VerticalResolution);
                using (Graphics g = Graphics.FromImage(source))
                    g.DrawImageUnscaled(original, 0, 0);
                source = original;

            // Lock source bitmap in memory
            BitmapData sourceData = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            // Copy image data to binary array
            int imageSize = sourceData.Stride * sourceData.Height;
            byte[] sourceBuffer = new byte[imageSize];
            Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);

            // Unlock source bitmap

            // Create destination bitmap
            Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppArgb);
            //Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed);

            // Lock destination bitmap in memory
            //BitmapData destinationData = destination.LockBits(new Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
            BitmapData destinationData = destination.LockBits(new Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            // Create destination buffer
            imageSize = destinationData.Stride * destinationData.Height;
            byte[] destinationBuffer = new byte[imageSize];

            int sourceIndex = 0;
            int destinationIndex = 0;
            int pixelTotal = 0;
            byte destinationValue = 0;
            int pixelValue = 128;
            int height = source.Height;
            int width = source.Width;
            int threshold = 500;

            // Iterate lines
            for (int y = 0; y < height; y++)
                sourceIndex = y * sourceData.Stride;
                destinationIndex = y * destinationData.Stride;
                destinationValue = 0;
                pixelValue = 128;

                // Iterate pixels
                for (int x = 0; x < width; x++)
                    // Compute pixel brightness (i.e. total of Red, Green, and Blue values)
                    pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3];
                    if (pixelTotal > threshold)
                        destinationValue += (byte)pixelValue;
                    if (pixelValue == 1)
                        destinationBuffer[destinationIndex] = destinationValue;
                        destinationValue = 0;
                        pixelValue = 128;
                        pixelValue >>= 1;
                    sourceIndex += 4;
                if (pixelValue != 128)
                    destinationBuffer[destinationIndex] = destinationValue;

            // Copy binary image data to destination bitmap
            Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);

            // Unlock destination bitmap

            // Dispose of source if not originally supplied bitmap
            if (source != original)

            // Return
            return destination;
2/22/2009 12:34:25 PM

Hi e_kreda,

 Thanks for your wonderful code. I am new to .Net. Can you please tell me Where to go

I am using MS Visual Studio 2005.

File --->New--> Project or File---> New ----> Website or File --> New ---> File.

 Where to go .ie.,Window application or console application or web form or web user


Please give some ideas.




2/23/2009 4:48:46 AM


Hi e_kreda,

 Thanks for your wonderful code. I am new to .Net. Can you please tell me Where to go

I am using MS Visual Studio 2005.

File --->New--> Project or File---> New ----> Website or File --> New ---> File.

 Where to go .ie.,Window application or console application or web form or web user

Please give some ideas.



This article may help

Beginning Programming with the Visual Studio 2005 Environment


Sandeep Kumar

MCPD - Web Developer
MCTS - .NET Framework 2.0: Web Applications
Software Associates

2/23/2009 5:18:52 AM

Similar Artilces:

How to convert .tiff image file to .pdf file without using any 3rd party tool using
HI allI have a urgent requirement i want to convert .tiff image to .pdf file Thanks in advance Regards RaviPlease click "mark as answer" if this post helped you. I dont think its possible without doing a lot of code or using third party tools, but if you  are looking for a free tool you can try a combination of Thanks and RegardsS.K.Vignesh----------------------Do remember to "Mark as answer" for this pos...

How to use VB.Net Files in C# Project and Compile All project to Only One Assembly File.?
Hi all,I have a Library of Useful Functions and procedures But in VB.Net Language(*.vb not *.dll).All the time i have to Add additional Project to my current Project and add that VB.Net Library to it ,Then Compile it and Reference it to  my C# project and use it .so as a consequence,After Compilation in the "Bin" directory i have additional assembly Related to that VB.Net Class Library rather than one.I want to know is there any way to Achieve only One Assembly Not Two. Thanks In Advance.Regards.Nothing Is Quite Impossible !!!...

Sending SMS using or using or
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

use VB.NET and C#.NET code in the same C#.NET project
All-- Here is a sample that is "off the beaten path", (at least for me). Is it possible, in an ASP.NET application, using the code-behind page building technique, to have both pages written in VB.NET and pages written C#.NET?At there is a sample that shows that, (contrary to popular belief), it IS possible to mix ASP.NET pages built with C#.NET with ASP.NET pages built with VB.NET in the same VS.NET 2003 project. Note that this is just a "fun" sample to see if it can be done and I do not recommend this practice as a "standard" way of develo...

COnverting image file into PDF file in C#.NET
hi friends, i have a problem in creating a PDF file from an image file. first of all pls clarify what is the internal concept in converting to PDF file. if nay one knows pls mail me the related code if you find any solution pls mail me at thank u all hari babu...

How to convert C#.Net code to VB.Net code ???...
HI, i was searching something new, then i suddenly find some tips to convert C#.Net code to VB.Net but i did not do well. i am puttint its url here plz tell me how to convert C#.Net code to VB.Net. Jasim...Please remember to click “Mark as Answer” on the post that helps youJasim AkhtarNew Delhi ( INDIA ) It would be better if you write the problem you having, while converting from C# to VB.NET. You cannot completely rely on online converters. ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Bl...

How Convert MHT File To HTML File(c# source code)
I Have Big Problem, Please Help Me!! I want Convert a MHT File To HTML File. I Search In Many Of Sites But All Off Them Only Convert HTML TO MHT!!! I Have C# Code(with source code) For Solve This Problem. (I Have Almost Function Similar TO function(mht,html) Meanse MHT filename -->HTML file and contents ) Please Ansewer To My Question Quickly . Very Thank My Mail : MAHDI_FAHMIDEH@YAHOO.COM ...

outlook file DBX file extract using
hi i want to read email in dbx file using plase help me .... Dear, U can see the below link: Regards,Saurabh Sharmaonly dead fish swim along the flow of river, learn to make your own way.Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread...

How to Create .mdb file from Excel file using
Hi all I want to create .mdb file that i have created excel feel from MS jet Database... through code behind Help me in this..  Regards RaviPlease click "mark as answer" if this post helped you. How to create an mdb file programmtically: to import Excel data into it: Regards Mike [MVP - ASP/ASP.NET]My site...

converting 2003 files to 2005
Hi, i am beginner..i watch videos about made on 2003 when i wrote these codes in 2005 ,it gives there any program which convert the code automatically?   thanks,Thanks,Speranza What videos are you talking about?  There are lots of great, up-to-date ASP.NET Videos on this site for free.Darrell Norton, MVPDarrell Norton's BlogPlease mark this post as answered if it helped you! i am talking about videos..Thanks,Speranza Speranza:they made on 2003 when i wrote these codes in 2005 ,it gives there a...

How can i print a .tiff file from C# code
Hi All, I am developing a web application using and c#. can anybody please let me know how can i print a .tiff file on click of a "Print" button on my web page. i do not want this file to be opened rather i just want it to send to the printer directly.   Regards, RashidThanksRashid AnsariEmail : remember to 'Mark as Answer' if this post answered your question! Hi,where do you want to print it? On the server where the image is or on the clients printer? If the latter's the case you won't ...

unintelligible file name when using Response to download a file.
I have a website that shows a list of files stored in the server. Here is the code:Dim ObjFileinfo As New FileInfo(strRootPath) Response.Clear() Response.AddHeader("Content-Disposition", "attachement;filename=" & strFileName) 'NOTE: strFile Name contains the name in Russian, if I Response.Write(strFileName)'I get the proper Russian name displayed on the page so I am sure that I am passing the right oneResponse.AddHeader("Content_Length", ObjFileinfo.Length.ToString()) Response.ContentType = "application/octet-stream" Response.Transm...

Unintelligible file name when using Response to download a file.
I have a website that shows a list of files stored in the server. Here is the code: Response.ContentType = "application/ms-word"Response.AddHeader("Content-Disposition", "attachment;filename=" & strFileName) Dim fs As FileStream = New FileStream(strRootPath, FileMode.Open, FileAccess.Read)Dim fileData As Byte() ReDim fileData(fs.Length)Dim bytesRead As Long = fs.Read(fileData, 0, CInt(fs.Length)) fs.Close() Response.BinaryWrite(fileData) Response.End()The problem is that when the files are written in Russian or Chinese the file name appears unintell...

serialize a XML file to a VB.NET file (class) using xsd
Hello   I would like to serialize  a XML file to a VB.NET  file (class).   How can I use XSD.exe  to generate my xml file  C:\leye_g\Travaux\Fichiers de données\test.xml  to a VB.NET File ?   Best regardsf Hi XML Schema Definition Tool (Xsd.exe)  can generate runtime classes from  XSD files . XmlElementAttribute Is Missing for the Generated Class Members While Using Xsd.exe describes how to generate class from xml and reports a problem. And you could find more info here: Code Generation in the .NET Framework Using XML Sch...

Web resources about - How to convert a Color tiff file to Black and white tiff file using vb/C# code? -

List of converts to Buddhism - Wikipedia, the free encyclopedia
Ajahn Brahm (born 1951), Religious teacher and student of the late Thai monk Ajahn Chah . Currently he is the abbot of the Bodhinyana Monastery, ...

Facebook Timeline For Pages: 8 Million Converts, 29 Million To Go
... reach to 98 percent of users who liked its page, as well as to double its engagement rate, during a 28-day period. Dr. Pepper hasn’t yet converted ...

Facebook stock roundup: Execs offload more stock, directors convert shares
... Bowles, the former co-chair of the now-defunct National Commission on Fiscal Responsibility and Reform, and Reed Hastings, Netflix CEO, converted ...

How to Convert Leads Into Buying Customers - The 9 Step Sales Process EVERYONE Should Use
... School of Business in Toronto on the topics of Sales and Entrepreneurship. I shared with them the sales process that I find How to Convert Leads ...

Bitcoin : Should I convert my savings to Bitcoin?
Answer (1 of 7): You should think of this question as "Should I invest all my savings in Bitcoin?", and not "Should I have my savings denominated ...

Coordinates - Calculate and Convert a Position on the App Store on iTunes
Get Coordinates - Calculate and Convert a Position on the App Store. See screenshots and ratings, and read customer reviews.

Catholics should not convert Jews, says Vatican, in push against anti-Semitism
... 50 years since the Vatican's repudiation of the concept of Jewish guilt for Jesus' death.  Vatican City: Catholics should not try to convert ...

Today’s apps gone free: BlockBear, Stock Grader, PDF Smart Convert and more
Block ads and other annoying content, take the emotion out of investing, and convert almost anything into a PDF with todays collection of apps ...

Ford patents rear wheel that converts into a unicycle
Filed under: Government/Legal , Green , Ford , Green Driving , Motorcycle , Electric Ford is thinking about allowing drivers to remove a rear ...

How to convert your old VHS tapes to DVD with this software
Remember those old VHS tapes you have sitting in the corner? Convert them into DVDs with this affordable software so you can easily watch them ...

Resources last updated: 1/10/2016 3:37:16 PM