Converting Bitmap Resources from .RC format to .resources format

If you want to be able to use bitmap resources using the VCL.Net TBitmap.LoadFromResourceName method you have to have them in .resources format.  This presents a problem when you are trying to convert a Win32 component that has its resources in .RC format.   You can import the .RC file into your component using the $R directive but LoadFromResourceName will not find the bitmaps because they were not imported from a .resources file.  This means that you somehow have to convert the .RC file to a .resources file.  I did quite a bit of searching but was unable to find a utility to do this.  Fortunately, it is quite easy to create your own.

This is done is two steps.  First, create a Win32 application to export the bitmap resources contained in the .RC file to .BMP files.  Then create a .Net application to import the .BMP files into a .resources file.  Both programs come to not much more than 20 lines of code in total.

Win32

{$R ESBASE.RC}

procedure ConvertToBMP;
const
// array of resource names contained in .RC file
RES_NAMES: array [1..8] of String =
( ‘ESTODAY’, ‘ESDOWNARROW’, ‘ESLEFTARROW’, ‘ESRIGHTARROW’,
‘ESSMALLDOWNARROW’, ‘ESUPARROW’, ‘ESRIGHTARROWS’,
‘ESLEFTARROWS’ );
var
bmp     : TBitmap;
i       : Integer;
begin
bmp := TBitmap.Create;
try
for i:=Low(RES_NAMES) to High(RES_NAMES) do
begin
bmp.LoadFromResourceName(HInstance, RES_NAMES[i]);
bmp.SaveToFile(Format(’%s.bmp’, [RES_NAMES[i]]));
end;
finally
bmp.Free;
end;
end;

.Net

procedure ConvertToResources;
const
// array of BMP files to import
RES_NAMES: array [1..8] of String =
( ‘ESTODAY’, ‘ESDOWNARROW’, ‘ESLEFTARROW’, ‘ESRIGHTARROW’,
‘ESSMALLDOWNARROW’, ‘ESUPARROW’, ‘ESRIGHTARROWS’,
‘ESLEFTARROWS’ );
var
i       : Integer;
bmp     : Bitmap;
res     : ResourceWriter;
begin
res := ResourceWriter.Create(’esbase.resources’);
for i:=Low(RES_NAMES) to High(RES_NAMES) do
begin
bmp := Bitmap.Create(Format(’%s.bmp’, [RES_NAMES[i]]));
res.AddResource(RES_NAMES[i], bmp);
end;
res.Close;
end;
Quite simple actually.

Obviously there are other approaches to the problem.   You could import the .RC file into your component and retrieve the bitmaps using GetManifestResourceStream but this would involve a bit of messing around to get the result into a TBitmap.   Overall, my approach seemed the easiest to program and easiest to understand.  At least for my application.

Leave a Reply