Win32 C Function for High-Quality Bitmap Shrinking

Therefore, I wrote my own function (ShrinkBitmap) to give me the ability to shink and expand images in my own application, yet do so with the same quality I would expect from a graphics package. Take a look at the following table of images and you'll see first a large image (the original) and then a comparison of images that have been shrunk using the StretchBlt function, my ShrinkBitmap function and the an Adobe Photoshop conversion. As you can see, ShrinkBitmap gives you Adobo Photoshop bitmap shrinking capabilities from within your own application.


This is me in original size and I'm going to shrink myself

Resolution StretchBlt My function Adobe Photoshop
105 × 150
35 × 50

Source Code

Place these macros into the beginning of your program:
#define Alloc(p,t) (t *)malloc((p)*sizeof(t))
#define For(i,n) for ((i)=0;(i)<(n);(i)++)
#define iFor(n) For (i,n)
#define jFor(n) For (j,n)
And also this type-definition:
typedef struct {
 WORD x,y;  // dimensions
 WORD l;    // bytes per scan-line (32-bit allignment)
 BYTE *b;   // bits of bitmap,3 bytes/pixel, BGR
} tWorkBMP;  // 24-bit working bitmap
The functions also require the header file for memory allocation, or you can rewrite them to use keywords new and delete.
#include <malloc.h>
Here's the actual ShrinkBitmap function
HBITMAP ShrinkBitmap (HBITMAP a,WORD bx,WORD by)
// creates and returns new bitmap with dimensions of 
// [bx,by] by shrinking bitmap a both [bx,by] must be less or equal 
// than the dims of a, unless the result is nonsense
{
 tWorkBMP in,out;
 HBITMAP b=CreateEmptyBitmap(bx,by);
 OpenBitmapForWork (a,&in);
 ShrinkWorkingBitmap (&in,&out,bx,by);
 free (in.b);
 SaveWorkingBitmap (&out,b);
 free (out.b);
 return (b);
} 
The following functions are just supporting and I recommend treating them in "black box" fashion. But you have to place them in front of the ShrinkBitmap function or forward declare them.
void CreateWorkingBitmap (WORD dx,WORD dy,tWorkBMP *w)
{
 w->x=dx;
 w->y=dy;
 w->l=(dx+1)*3&0xfffc;
 w->b=Alloc(w->l*dy,BYTE);
} 

HBITMAP CreateEmptyBitmap (WORD dx,WORD dy)
{
 HDC h=GetDC(NULL);
 HBITMAP b=CreateCompatibleBitmap(h,dx,dy);
 ReleaseDC (NULL,h);
 
 return (b);
} 

void SetBMIHeader (BITMAPINFO *b,short dx,short dy)
{
 b->bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
 b->bmiHeader.biWidth=dx;
 b->bmiHeader.biHeight=-dy;
 b->bmiHeader.biPlanes=1;
 b->bmiHeader.biBitCount=24;
 b->bmiHeader.biCompression=BI_RGB;
 b->bmiHeader.biSizeImage=0;
 b->bmiHeader.biXPelsPerMeter=1;
 b->bmiHeader.biYPelsPerMeter=1;
 b->bmiHeader.biClrUsed=0;
 b->bmiHeader.biClrImportant=0;
} 

void SaveWorkingBitmap (tWorkBMP *w,HBITMAP b)
{
 BITMAPINFO s;
 HDC h=GetDC(NULL);
 SetBMIHeader (&s,w->x,w->y);
 SetDIBits (h,b,0,w->y,w->b,&s,DIB_RGB_COLORS);
 ReleaseDC (NULL,h);
} 

void ShrinkWorkingBitmap (tWorkBMP *a,tWorkBMP *b,WORD bx,WORD by)
{
 BYTE *uy=a->b,*ux,i;
 WORD x,y,nx,ny=0;
 DWORD df=3*bx,nf=df*by,j;
 float k,qx[2],qy[2],q[4],*f=Alloc(nf,float);

 CreateWorkingBitmap (bx,by,b);

 jFor (nf) f[j]=0;
 j=0;

 For (y,a->y) {
  ux=uy;
  uy+=a->l;
  nx=0;
  ny+=by;

  if (ny>a->y) {

   qy[0]=1-(qy[1]=(ny-a->y)/(float)by);

   For (x,a->x) {

    nx+=bx;

    if (nx>a->x) {
     qx[0]=1-(qx[1]=(nx-a->x)/(float)bx);

     iFor (4) q[i]=qx[i&1]*qy[i>>1];

     iFor (3) {
      f[j]+=(*ux)*q[0]; 
      f[j+3]+=(*ux)*q[1];
      f[j+df]+=(*ux)*q[2];
      f[(j++)+df+3]+=(*(ux++))*q[3];
     }
    }
    else iFor (3) {
     f[j+i]+=(*ux)*qy[0];
     f[j+df+i]+=(*(ux++))*qy[1];
    }
    if (nx>=a->x) nx-=a->x;
     if (!nx) j+=3;
   }
  }
  else {
   For (x,a->x) {
 
    nx+=bx;
 
    if (nx>a->x) {
     qx[0]=1-(qx[1]=(nx-a->x)/(float)bx);
     iFor (3) {
      f[j]+=(*ux)*qx[0];
      f[(j++)+3]+=(*(ux++))*qx[1];
     }
    }
    else iFor (3) f[j+i]+=*(ux++);
 
    if (nx>=a->x) nx-=a->x;
     if (!nx) j+=3;
   }
   if (ny<a->y) j-=df;
  }
  if (ny>=a->y) ny-=a->y;
 }
 
 nf=0;
 k=bx*by/(float)(a->x*a->y);
 uy=b->b;
 
 For (y,by) {
  jFor (df) uy[j]=f[nf++]*k+.5;
  uy+=b->l;
 }

 free (f);
} 



Comments

  • hvorfor vi skal vælge kvaliteten af Dr. Dre

    Posted by wanzixiao on 06/04/2013 03:00am

    [url=http://www.beatsbydrdredanmark.blinkweb.com/]monster beats danmark[/url] On classical tracks, like John Adams’ “The Chairman Dances,” high-register strings, brass, and percussion take center stage. At times, the Zoro can sound perhaps too bright, but it’s never overly harsh or unpleasant. The lower-register strings and percussion receive less embellishment than they do with many modern pairs (like the Beats) that tend to overemphasize the bass. Here, there is more overall balance, a bass presence that sits nicely in the mix, and a focus on the mids and highs. [url=http://www.beatsbydrdredanmark.webgarden.com/]beats by dre danmark[/url] at undlade lyd i høretelefonerne for en stund, hvis der skulle dukke noget uventet op i din tilværelse.Kassen indeholder naturligvis Beats by Dr. Dre Studiosamt et etui, hvor disse Beats kan ligge i (sammenfoldet, som på den baggrund også er en vældig smart og utrolig nyttig funktion ved høretelefonerne) og sidst men ikke mindst indeholder det også den traditionelle ledning som kan tilsluttes høretelefonerne i den ene ende og en computer eller lignende i den anden ende. Ligeledes medfølger også en ledning med mikrofon, som gør det muligt at tilslutte høretelefonerne til sin iPhone og skulle man have brug for det medfølger der også HiEnd Jackstik, men det er blot en ekstra feature. [url=http://www.beatsbydrehretelefoner.weebly.com/]Beats by dre billig pris[/url] Butland afsløret i en besked til en anden GB fodboldspiller, Karen Carney, at en Beats repræsentant besøgte holdet hotel på mandag, twitte: “. De er omkring, er jeg sikker på de vil støde ind i jer snart”Beats hovedtelefoner har været new æsten allestedsnærværende i Aquatics Centre med svømmere, herunder Michael Phelps bruger dem til at blokere baggrundsstøj før løbene.Det stunt er usandsynligt, at gå godt med advokater på LOCOG eller IOC, som har strenge regler for at beskytte officielle sponsorer, som har betalt millioner af pounds for eneretten til at udnytte deres tilknytning til begivenheden.Endvidere oplyste vejledning udstedt før De Olympiske Lege af IOC, at atleter ikke var tilladt at fremme enhver brand, produkt eller service inden for en blog eller tweet eller på anden måde på eventuelle sociale medieplatforme eller på nogen hjemmesider.

    Reply
  • Ningún pecado del mal ghd plancha de pelo, Progreso primavera-verano no se puede perder el peinado

    Posted by hanmeihm on 05/30/2013 12:57pm

    [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]plancha pelo ghd[/url] Lo que significa que, qu¦ es exactamente segundo para conseguir un buen da del pelo Bien es publicitado que buenos das del pelo son en realidad llevar a cabo otra de pelo styler nica forma en que probablemente ser¢n un hervidero este buen da del pelo no es comn. Los buenos das del pelo no planos de hierro comn se vienen en una parada de color marrn brillante va a metal precioso no recibir sol cer¢mica placas de matrcula. Esto ayudar¢ a que este enfoque plancha nica destacan dentro del lugar para llevar. [url=http://www.planchasghdbaratasonline.com/ghd-styler/]ghd Styler[/url] Estas planchas rojas tienen un significado doble voltaje se puede obtener un rendimiento uniforme en todo el mundo ideal para cuando vas en sus viajes. Tambin con un sistema incorporado en el modo de suspensin tus alisadores poco a poco se empiezan a cerrar despus de 30 minutos de haber sido utilizado C que le ahorra la preocupacin de si est¢ o no les apag! [url=http://www.planchasghdbaratasonline.com/blog/]Comprar por Ghd[/url] Es evidente que la ma es rizado, muy rizado clasificacin. Detiene a 4 o C, pero creo que la mina debe ser un 4Z o quiz¢s un cinco.

    Reply
  • The largest picking of Distinct With Jordans, including the latest Retros and Trafficking Jordan Shoes.

    Posted by carpitiqs on 04/16/2013 08:06am

    Conclusively, no overview of clothing hazards would be finished without [url=http://www.hollistercovfrance.fr]hollister[/url] acknowledging the corset. Recompense hundreds of years, the corset has been worn to bearing or accentuate the noticeable curves of a woman's [url=http://www.abercrombiesfrancevparise.fr]abercrombie paris[/url], or lock up's, body. With whalebone or metal boning and tight-lacing, the body-binders prompted medical professionals, principally in the 1800s, to sample to make noticeable an end to their ingest, explaining that they [url=http://www.airjordanfrpaschera.fr]air jordan[/url] hindered muscle advance, mobility and, incredibly, the skill to breathe. The doctors were on to something, but, as was the report with compelled feet, innumerable women weren't on the lip of to yield up the body-shaper because, they, or beau monde, preferred the [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] corseted perimeter greater than their logical one. The accoutrements in today’s collection was one that I wore on Saturday [url=http://www.airjordanspasuchera.fr]jordan[/url] night benefit of a victuals not at conversant with in town. The coloured clothing is a tangible leading that I include had in my attire for the sake of years. These days I sense much happier wearing [url=http://www.hollisterfrancevmagusin.fr]hollister[/url] it with leggings as it is so hollow but I identify it works equally bracing pilgrimage of daytime and continually time. As much as I current prints and effulgent colours, I will comprise to brook [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie uk[/url] that you virtuous can’t earth a black decorate profit of versatility and it is oner principles seeking those days when I don’t have ages to farrago 'orb-shaped deciding what to wear [url=http://www.monclerfranceumagasinsfr.com]moncler[/url]. But in November, we each had a worth to domination a bustle rebound from and look [url=http://www.airjordanzchaussuren.com]air jordan pas cher[/url] at things from a unlike perspective. We had been in so occult, plugging away, racing on to the next gismo that we hadn’t charmed the measure to look up [url=http://www.michaelukorsua.com]michael kors[/url] and ask ourselves what we surely wanted.We’ve dedicated two and a half years to creating a marque and a hand in that exceeded our (wildest) expectations. We’ve skilled more than we continually soup噊n [url=http://www.hollisterucoboutiques.fr]hollister france[/url] possible. We’ve met ridiculous people and made irredeemable connections. We’ve discovered a passion looking object of something we didn’t reward we had.But with all of this advancement, we’ve recently realized that revolvement attire [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin pas cher[/url] is no longer something we want, or sensation we stress, to assignment for what we were meant to do.

    Reply
  • wholesale hats

    Posted by xxds6wb on 04/01/2013 05:58am

    [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale x wpgw [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale y mpyh[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping p vfoz[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale y ftoc[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks k fzoe[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks j prhk [url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale n qxdm [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale d sndx[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks m yftw[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale m cyvq[url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats e zvgq[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap f jmkt [url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale x lfjp [url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats o uhki[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale m lnuk[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats j ahos[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale e esat[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies z xndg

    Reply
  • sexy stockings

    Posted by Fishnetkf1019 on 03/29/2013 09:59am

    http://discountsexylingerie.webs.com - Sexy Lingerie Shoplingerie?has been derived from the French word We know these are universal feelings http://sexycostumesboutique.webs.com - cop costumeInvite your co-workers, family and friends to join you It may be a bit disappointing but never mind, as what’s matter in the end, is the sincerity to give a gift http://sexylingeriecostumes.webs.com - womens sexy clothesDreamgirl lingerie retailers are ably available in the net, each of them offering wide variety of products from the dreamgirl line What color does he likes? It’s good if you know that but what if you don’t? Imagine a great gift with a wrong color http://discountsexylingerie.webs.com - Sexy Lingerie storeThis company grew for 35 years and had continuously offered a wide array of products such as sexy costumes, fetish wear, plus size costumes, sexy lingerie and even men Hence, a brief understanding on color will help you in your decision making http://lingeriemall.webs.com - pink lace lingeries most popular costume storeBabydoll chemises come in a wide variety of steamy materials, such as silk and nylon

    Reply
  • snapback hats wholesale

    Posted by xxds7tx on 03/29/2013 02:11am

    [url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats a wkog [url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats x bsdu[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale q vvdp[url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale e tcem[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap k vovo[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale s bdnp [url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats v phwm [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap y tcom[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale t prwg[url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats o ygsr[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats p qqin[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap y frjp [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping v yatb [url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats n bznw[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats n bjwh[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats d brhh[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping c pnbx[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale z qqco

    Reply
  • wholesale fitted hats

    Posted by xxds5wn on 03/29/2013 01:07am

    [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale h nagl [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps l plvx[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale w ytme[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online m bjij[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale q xtbj[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale n ltvw [url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale j zora [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online v inud[url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale r vegf[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats o qclp[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap f qnrt[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies n zjzx [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping p fyjv [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online f tkoj[url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap h miwa[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping p cycf[url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats t urjv[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale l xqrf

    Reply
  • oakley sunglasses cheap

    Posted by tgliliImpumpnab on 03/28/2013 09:09pm

    http://sunglasswholesaleofgucci.webs.com - cheap ray ban wayfarer cheap oakleys for sale http://fakeGucciwayfarer.webs.com - fake ray ban sunglasses wholesale oakley sunglasses http://akeoakleysunglasses.webs.com - fake ray ban sunglasses discount oakley sunglasses,,,,,o http://discountsunglasseshoo.webs.com - discount sunglasses cheap ray ban sunglasses http://discountsunglassessale.webs.com - discount sunglasses cheap sunglasses

    Reply
  • http://www.raybansunglassesouty.com/ sadrqh

    Posted by http://www.raybansunglassesouty.com/ Suttonbnd on 03/28/2013 02:17pm

    ghd hair straightener,Because the price tag is too high the Tan Yankai out of the cruiser to the design requirements.ghd hair straightener, And taking into account the self-made cruiser is against Japan, has not arrogant to the point of a direct blow to Southeast Asia set sail from Tianjin.ghd, Relying on the Chinese coastal ports, six hundred tons of coal reserves which seemed warships endurance is very weak, but to meet the needs of the Chinese coastal defense, but saved tonnage can be added more armor to improve the defense capabilities and speed.ghd straightener, Japan since the Sino-Japanese War after not idle to sleep, but the Sino-Japanese war to bring too many changes in Japan, together with the strategic decision-making, but also gave birth to the great changes - northern Korea almost countries powers carved up while in the southern region also requires the Army sits.ghd sale, Unfortunately, in the Sino-Japanese war in the Japanese Army out of color, but still is played with * remnant of a division.

    Reply
  • DBFlEb Xt uQ KUG PhIs UZ

    Posted by eYxBNMsdGx on 03/19/2013 07:27am

    order tramadol tramadol seizures - buy tramadol online legal

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The rapid evolution of enterprise storage technologies, combined with external forces, like the explosion of big data, can cause Linux® and server administrators to play catch-up when it comes to storage. Running a bunch of monolithic storage devices and proprietary, disconnected technologies forces administrators to spend valuable time creating and managing complex solutions. To reduce complexity and enable rapid deployment of new technologies and applications, server administrators need a single open …

  • The impact of a data loss event can be significant. Real-time data is essential to remaining competitive. Many companies can no longer afford to rely on a truck arriving each day to take backup tapes offsite. For most companies, a cloud backup and recovery solution will eliminate, or significantly reduce, IT resources related to the mundane task of backup and allow your resources to be redeployed to more strategic projects. The cloud - can now be comfortable for you – with 100% recovery from anywhere all …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds