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

The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
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 »

Price Scanner via MacPrices.net

Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
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

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular 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
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.