Question

Using LIbTiff to convert a monochrome tiff to 1 bit bitmap

Asked by: johanzn

I am trying to use LibTiff to convert a monochrome TIFF to a 1 bit BMP image.  The TIFF image is coming into the dll as a pointer.  I have overrode the LibTiff read functions so that I can handle that portion in memory.  The problem is that the return from the TIFF functions is 24bit and not 1 bit.  Since I am trying to replace a function that has always returned a 1 bit BMP, I need to keep the return image the same.  I need to either replace the put function (put1bitbwtile2) with one that will return a 1 bit BMP or convert it after the fact to 1 bit.

Option 1: Convert after the fact from 24 bit to 1 bit
TIFFReadRGBAImage(tif, width, height, inbuf, 0);
 
Option 2: Replace the put function
if (TIFFRGBAImageBegin(&img, tif, 0, ErrorMsg))
{
	img.put.contig = &put1bitbwtile2;
	img.req_orientation = 4; //Bottom Left
	TIFFRGBAImageGet(&img, inbuf, img.width, img.height)
	TIFFRGBAImageEnd(&img);
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-09-11 at 10:59:15ID23723940
Tags

C/C++

Topics

C Programming Language

,

Microsoft Visual C++

,

C++ Programming Language

Participating Experts
2
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. *.TIFF again
    I have to handle the bitmaps for thousands of *.TIFF file, which meant this must be done automatically by my VB codes. But VB does not support opening *.TIFF and I don't wanna mess up with decoding it myself. How can I use any OCX that opens TIFF file and save it as other ima...
  2. convert bitmap to monochrome bitmap vb.net
    how can i convert any bitmap to a monochrome bitmap. I am using this code from planet source code and have got it all working. There is a bug with the imgext it returns the extensions of all types of that image type but i have modified it to pull the first extension of th...
  3. Tiff Annotations
    I'm writing a program in vb.net which takes tiff files generated by another application, creates one tiff file, and then faxes them. This other application has the option to annotate the tiff files, and I would like to be able to fax those annotation on top of the main tiffs....

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: FentonEngPosted on 2008-09-11 at 11:16:28ID: 22452822

If you have the RGBA data in memory, then simply write a 1 or 0 into a boolean array depending on the value in the alpha channel (eg. 0 for 0 alpha, 1 for everything else)

This can then be packed into bytes and written to a bitmap using either your own function or a Win32 library function such as:

http://msdn.microsoft.com/en-us/library/ms532305(VS.85).aspx


From the top of my head, a good way would be to scan 8 pixels (alpha channels) at a time and build a byte from the results, rather than having a bool array and packing later on. You could even do the whole thing with simple shift operations!

Once you have that sorted, you could speed up your routine by handling 32 pixels at a time and writing 4-byte unsigned integers to the bitmap.

Unless I have mis-understood your question...

 

by: trinitrotoluenePosted on 2008-09-11 at 11:55:31ID: 22453301

check the following links, might help out in giving you some ideas. Since these links are MS specific you will have to devise a scheme for the library you are using.....

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.tiffbitmapdecoder_members.aspx
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.tiffbitmapdecoder.aspx

 

by: FentonEngPosted on 2008-09-11 at 12:05:58ID: 22453426

Those are good links, bear in mind they are for the .NET environment as there are no .NET tags in the question?  If you are using managed code, then there are certainly built in solutions for this problem already, as demonstrated by trinitrotoluene

For anyone else wishing to assist with the solution I came across some documentation for LibTiff:

http://www.libtiff.org/

and the TIFF specification (version 6 here)

http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf

If you have the access to the pixel data in memory, I don't really "see" the problem you are having, apart from the conversion mechanism itself, which I have briefly out-lined for you and will flesh it out if you wish.

 

by: johanznPosted on 2008-09-11 at 12:59:35ID: 22454033

Sorry, I wasn't clear in the original post.

This is a native dll, so .Net will not help.  I would have been done a long time ago if it was.  The original function is in inline assembly and has some issues with some images.  So I am trying to get it into C/C++ to make it easier.  

The conversion is the problem I am having.  I am using the code below to get from 24 to 8, but I just don't understand the shift operator that well to get it to 1 bit.  "width " is the length of each line in the image.  "height" is the number of rows in the image.

char *buffer;
int i,j;
 
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{   
buffer[j] = ((uint32)(TIFFGetR(buf[j]))|((uint32)(TIFFGetG(buf[j]))<<8)|((uint32)(TIFFGetB(buf[j]))<<16)|(uint32)(0xffL<<24));
}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: FentonEngPosted on 2008-09-11 at 15:54:54ID: 22455858

Ok no worries. I am not familliar with the LibTiff data, but I assume the 24 bit pixel data is either one of the two 24 Bit formats

24 Bit RGB [8-8-8] Big Endian
16 Bit RGB + Alpha RGBA [5-6-5-8] Big Endian

Being as there is no TIFFGetA call in your snippet, I am going to assume the format is RGB Big endian 24 bit, please correct me if this is not the case.

For simplicities sake, I would start off with a boolean array for the bitmap data (can cover packing later on)

that is:

bool *data = (bool*) new bool[Width * Height]; // assuming width and height are valid

I am going to use "pix" to represent a 32 bit integer which will hold the TIFF pixel data (as I do not know exactly how it comes from the file, you should be able to translate this into your code)

that is:

unsigned __int32 pix; // or just int as long as your compiler treats it as four bytes long

in the pix variable the data should be stored as follows (remember I have assumed big endian, you will need to correct me if i am wrong)

0xABGR < Note that even though you aren't using the alpha channel, there will still be *something* stored there, even if it is junk

Bits 0-7 Alpha, (probably 0xFF for your 24 bit pixel data), [extraction: pix & 0xFF]
Bits 8-15 Blue,             [extraction: (pix >> 8) & 0xFF]
Bits 16-23 Green,       [extraction: (pix >> 16) & 0xFF]
Bits 24-31 Red,           [extraction: (pix >> 24) & 0xFF]

The first order of business is to check for *any* colour in the current TIFF pixel, to assign a "1" to the bitmap data and "0" if there is no colour data (all zero). You can tune this how you like to pick out transparent colour keying, or for using black as a transparent colour.

ie:

if( ((pix >> 8) & 0xFF) || /* NOTE: I ignored the alpha for your case, as it is unused */
    ((pix >> 16) & 0xFF) ||
    ((pix >> 24) & 0xFF))
{
   // put a 1 in the array ie data[some index] = 1
}
else
{
   // put a 0 in the array ie data[some index] = 0
}

Then you need to pack the bool array into a byte array to pass it to either CreateBitmap or any other creation function, as very few (if any) will accept boolean arrays


Pseudocode:

Loop Index through array in 8s

   Current byte = 0

   Loop n from 0 to 7
       Current byte &= byte(data[index + n]) << n
   Next n

Next Index

The inner loop of that algorithm effectively does this:

Assuming the next 8 pixels are 1, 1, 0, 0, 1, 0, 1, 0

n       Current Byte      data [...]       byte(data[...])   shifted by n          ANDed

0         00000000             1               00000001      00000001           00000001
1         00000001             1               00000001      00000010           00000011
2         00000011             0               00000000      00000000           00000011
3         00000011             0               00000000      00000000           00000011
4         00000011             1               00000001      00010000           00010011
5         00010011             0               00000000      00000000           00010011
6         00010011             1               00000001      01000000           01010011
7         01010011             0               00000000      00000000           01010011


That alrogithm will pack the booleans together in groups of 8, this should then leave you with an array of bytes with which to build a bitmap. I'll leave it up to you to work out the rest (left over bits, different pixel formats etc...)

Don't forget to delete any temporary memory usage before you return and let me know how you get on.

Excuse the ASCII

 

by: johanznPosted on 2008-09-17 at 11:38:55ID: 22502148

FentonEng,

That was the explaniation  I needed.  LittleEndian-BigEndian was involved, so I am flipping the bits as I compress it to 1 bit.

Thanks

TIFFReadRGBAImage(tif, width, height, inbuf, 0);
for (i = 0; i < (int)height; i++)
{
   unsigned int *buf = inbuf + i * width;
   for (j = 0; j < (int)width; j++)
   {
      if (/*Red*/(buf[j] & 0xff) || /*Green*/((buf[j] >> 8) & 0xff) || /*Blue*/((buf[j] >> 16) & 0xff))
      {
	pData[iBufferLength] = pData[iBufferLength] | 1 << (7 - (j % 8));
	if ((j % 8) == 7)
            iBufferLength++;
      }
      else
      {
	pData[iBufferLength] = pData[iBufferLength] | 1 << (7 - (j % 8));
	if ((j % 8) == 7)
	    iBufferLength++;
      }
  }
iBufferLength++;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: johanznPosted on 2008-09-17 at 11:40:14ID: 31495646

I know understand the shift operator better.   Thanks.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...