TweetFollow Us on Twitter

MacPaint files
Volume Number:1
Issue Number:7
Column Tag:C Workshop

MacPaint file format

By Keith McGreggor

The MacPaint file format is rapidly becoming the standard for transferring graphic information from one application to another. This article will explain that format and show you how to transfer your own images into MacPaint files.

A Little Bit of QuickDraw

The Macintosh’s screen is a bit image. That is, what appears on the screen is actually a collection of consecutive bits in memory that the hardware in the Mac interprets as screen dots (or pixels). If the value of one of these bits is 1, then the pixel corresponding to it will be black. If the bit is 0, then the pixel will be white.

Figure #1. Bits represent pixels

The Mac screen is 512 pixels wide by 342 pixels tall. The bit image in memory takes up 175,104 bits (or 21,888 bytes with 8 bits per byte). We can consider the screen bit image as being 342 rows with 64 bytes per row. Due to the 68000 microprocessor in the Macintosh, every bit image must have an even number of bytes per row, and the rows must begin and end on word boundaries.

In C, the easiest way to define a bit image is with an array of characters. For example, if we wanted to define the Macintosh screen’s bit image, the definition would be:

Figure #2. C definition of a bit image

Bit images are manipulated by Quick- Draw through the use of bitmaps. A bit- map is a structure which points to a bit image and associates a coordinate system with it. The definition of a bitmap is:

Figure #3. C definition of a bitmap

The baseAddr field points to the first byte (character) in the bit image. The rowBytes field contains the number of bytes per row in the bit image. The rectangle bounds provides the coordinate system for the bits. The top left corner of the rectangle is aligned with the first bit of the bit image.

Since we can treat bit images in C as arrays of characters, we don’t always have to display them immediately. You can easily create a picture in a bit image off-screen, and later in your program “stamp” it onto the Mac’s screen.

The Macintosh’s ROM contains several QuickDraw calls that allow you to manipulate bitmaps (on- or off-screen). We’ll look at two of these later in the program.

MacPaint images are kept in the data fork of a MacPaint file. The file is essentially a 512 byte header followed by a bit image that is 576 pixels wide by 720 pixels tall (or 72 bytes by 720 rows).

Figure #4. The MacPaint File Format

The 512 bytes of header contain version information, pattern definitions, and an unused area for future expansion. If you change the contents of this section with care, you can set up your own patterns. If the version number is zero, the default patterns are used. If the number is not zero, then the patterns in the header are used.

Fig.#5.The Paint File Header Format

The MacPaint file bit image is considerably larger than the Macintosh screen’s bit image. In fact, if you were to store a bit image 72 bytes by 720 rows directly onto disk, each MacPaint file would take a minimum of 52K bytes! To make these files smaller, each row of pixels has been compressed using the PackBits routine in the Macintosh ROM. Using PackBits, the typical MacPaint file compresses down to around 10K bytes.

Dipping in the Bit Bucket

To make your program transfer an image into a MacPaint file, you need only to copy the bitmap containing the image into the compressed MacPaint file format. To be able to do this, you need to use two ROM routines, CopyBits and PackBits.

CopyBits transfers the contents of one bitmap into another. If you want, you can specify a mask region in the destination bitmap to prevent CopyBits from destroying the entire image. CopyBits will shrink or expand the contents of the source bitmap to fit the destination bitmap’s rectangle. To call CopyBits from C, use this format:

Figure #6. Calling CopyBits from C

where “copymode” is one of the source transfer modes:

Figure #7. Source Transfer Modes

PackBits compacts a string of bytes by compressing runs of equal bytes. You call PackBits from C like so:

Figure #8. Calling PackBits from C

where “numbytes” is the number of bytes pointed to by “srcPtr.”

Initially, “dstPtr” should point to the first destination byte. The PackBits routine will move “dstPtr” to point to the next available byte. To find out how much space the original bytes were compacted into, you need to subtract the original location of “dstPtr” from its current location.

Fig. #9 How PackBits moves “dstPtr”

About the Program

This program will demonstrate how to “cut” a part of an image into a MacPaint file. It is written for the Consulair Mac C system and Toolkit. You’ll probably need to change things a bit to make it work with other versions of C.

The program opens a single window and draws a few inverted rectangles in it. Then, a gray flashing rectangle will appear and follow the position of the cursor. Use the mouse to position this rectangle where you want, and then press the mouse button. The image inside the rectangle will be cut from the screen (using CopyBits) and transferred into a MacPaint file called “DummyFileName” (using repeated calls to PackBits).

The key routine, MakePaintFile, takes as input a C string containing a filename, and a pointer to a bitmap of arbitrary size. It then creates that file (if possible) on the active disk drive, sets the file signature and type to a MacPaint file type, and compresses that bitmap into the file using PackBits. If the bitmap is smaller than 576 by 720 (as will usually be the case), the bitmap is padded with white space. If the bitmap is larger than 576 by 720, the bitmap is clipped to 576 by 720.

/*
 * MakePaint.h
 *        a C routine to create a MacPaint file
 *        from a given bitmap
 *
 * (c) 1985 by Keith McGreggor for MacTutor
 *       
 */

#define WRITEONLY 7

MakePaintFile( myfilename, mybitmap )
char myfilename[63];
struct ABitMap *mybitmap;
{
 char dstbuf[511],srcbuf[511];
 char *srcPtr;
 char *dstPtr;
 char *mypointer;
 short i,j,dstBytes;
 FILE myfile;
 short t,b,vsize,hsize;
 
// attempt to create the file
 
 myfile = creat( myfilename, WRITEONLY );
 if (myfile != 0) {

// turn the file into a MacPaint file
// and write out a 512 byte header
// full of zeros (we’re not using any of
// our own patterns)

    SetFileSignature(myfilename,’MPNT’); 
    SetFileType(myfilename,’PNTG’);
    for (i = 0; i < 512; i++) fputc(0,myfile);

// figure out how big the bitmap is and set up
// a general pointer to the bit image

    mypointer = mybitmap->baseAddr;
    hsize = mybitmap->rowBytes;
    vsize = (mybitmap->bounds.bottom)
                        - (mybitmap->bounds.top);

// now, write out 720 rows of bytes

    for (j = 1; j <= 720; j++) {

// reinitialize source and destination pointers

 srcPtr = &srcbuf[0];
 dstPtr = &dstbuf[0];

// copy the next row of bytes into srcbuf[],
// clipping or expanding where necessary

 for (i = 0; i < 72; i++) {
        if ((i < hsize) && (j <= vsize)) {
      srcbuf[i] = *mypointer;
           mypointer++;
           }
            else srcbuf[i] = 0;  // 8 white bits
 }

// compress srcbuf[] into dstbuf[]

 #PackBits(&srcPtr,&dstPtr,72);

// figure out how much compression occurred 
// and write those bytes out to the file

 dstBytes= (short)(dstPtr-&dstbuf[0]);
 for (i = 0; i < dstBytes; i++)
                   fputc(dstbuf[i],myfile);
    }

// all 720 lines have been written, so
// close up everything and return

    close(myfile);
 }
}




 /*    CutToPaint.C
  *      A sample program to illustrate
  *      the use of PackBits and CopyBits
  *
  * (c) 1985 by Keith McGreggor for MacTutor
  */
  #Options -N
  #include “Stdio.h”
  #include “MacCdefs.h”
  #include “Window.h”
  #define TRUE 0xFF
  _#define BUTTONNOTPRESSED !#Button()
  #define GRAY &(QD->gray)
  
  // allocate the application’s window
  
  WindowPtr mywindow;
  Rect mywindowrect = { 40, 5, 300, 507 };
  
  // allocate the tracking variables
  
  Rect trackingrect{0,0,100,100};
  short globx,globy,incx,incy;
  
  // allocate a bitmap and bit image to
  // hold the cut bits
  
  struct ABitMap{
   char *baseAddr;
 short  rowbytes;
 Rect bounds;
 };
 
  struct ABitMap targetmap;
  char theactualbits[14][100];
  
  #include “MakePaint.h”
  /* ------------------------------------*/
  // draw some inverted rectangles
  // just to have something to “cut”
  
  DrawSomeStuff()
  {
  Rect temprect;
  short i;
  
  #MoveTo(10,240);
  #DrawString(“\020Press the button!”);
  for (i=0;i<200;i += 10) {
   #SetRect(&temprect,i+20,i+20,i+100,i+40);
 #InvertRect(&temprect);
 }
  }
  
  /*------------------------------------*/
  // Open a window for drawing
  // and do general housekeeping
  
  InitializeOurSystem()
  {
  #InitDialogs(0);
  mywindow = (WindowPtr)#NewWindow(0,  &mywindowrect,”\021A Window for 
bits”,  TRUE,0,-1,TRUE,0);
  #SetPort(mywindow);
  DrawSomeStuff();
  #FlushEvents(-1,0);
  #InitCursor();
  #PenSize(2,2);   // set up pen for
  #PenMode(patXor);  // drawing the
  #PenPat(GRAY);   // ghost rectange
  }

  /*------------------------------------*/
  // Draw the ghost rectangle
  
  DrawCurrentPosition()
  {
  #FrameRect(&trackingrect);
  }

  /*--------------------------------------*/
  // Find out where the mouse is and
  // update global variables
  
  GetNewMouse()
  {
  Point mypoint;
  
  #GetMouse(&mypoint);
  #GlobalToLocal(&mypoint);
  incx = mypoint.h-globx;
  incy = mypoint.v-globy;
  globx = mypoint.h;
  globy = mypoint.v;
  }

  /*------------------------------------*/
  // move the ghost rectange to track
  // the motion of the mouse
  
  UpdatePostion()
  {
  #OffsetRect(&trackingrect,incx,incy);
  }
  
  /*------------------------------------*/
  // First, move around a ghost rectange
  // until the button is pressed.
  // Then, create a bitmap and copy
  // whatever is inside the rectange to
  // the bitmap.
  
  CutARectangle()
  {
  globx = 0;
  globy = 0;
  while (BUTTONNOTPRESSED) {
   DrawCurrentPosition();
 GetNewMouse();
 DrawCurrentPosition();
 UpdatePosition();
  }
  #FlushEvents(-1,0);
  #LocalToGlobal(&trackingrect.topleft);
  #LocalToGlobal(&trackingrect.botRight);
  targetmap.baseAddr = &theactualbits[0][0];
  targetmap.rowBytes = 14;
  targetmap.bounds.left = 0;
  targetmap.bounds.top = 0;
  targetmap.bounds.right = trackingrect.right-trackingrect.left;
  targetmap.bounds.bottom = trackingrect.bottom-   trackingrect.top;
  
  // mywindow -> portBits is the Macintosh screen bit image
  
  #CopyBits(&(mywindow->portBits), &targetmap,
   &trackingrect,
 &(targetmap.bounds),
 srcCopy,
 0);
  }
  
  /*------------------------------------*/
  // call makepaintfile to save the
  // bitmap away as a macpaint file
  // named “dummyfilename”
  // (note: see MakePaint.h listing)
  
  SaveItAway()
  {
  MakePaintFile(“DummyFileName”,&targetmap);
  }
  
  /*----------------------------------*/
  // Our main program
  
  main()
  {
   InitializeOurSystem();
 CutARectangle();
 SaveItAway();
 #ExitToShell();
  }
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.