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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several 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... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.