I use TSVGImageIcon to read SVG vector images, and I have created this routine to save an image as a bitmap of a certain size :
function SVG2Bitmap(Imatge: TBytes; x, y: integer): TBytes;
var SVG: TSVGIconImage;
Stream: TBytesStream;
Bitmap: TBitmap;
Resultat: TBytesStream;
Form: TForm;
begin
try
SVG := nil;
Form := nil;
Stream := nil;
Bitmap := nil;
Resultat := nil;
Stream := TBytesStream.Create(Imatge);
Stream.Position := 0;
Form := TForm.Create(nil); // The SVGIconImage raises an error if not inside a Form
SVG := TSVGIconImage.Create(Form);
SVG.Parent := Form;
SVG.Stretch := True;
SVG.Proportional := True;
SVG.LoadFromStream(Stream);
SVG.Width := x;
SVG.Height := y;
Bitmap := TBitmap.Create;
Bitmap.SetSize(x, y);
SVG.PaintTo(Bitmap.Canvas, 0, 0);
Resultat := TBytesStream.Create;
Bitmap.SaveToStream(Resultat);
Result := Resultat.Bytes;
finally
if Assigned(SVG) then try SVG.Free except end;
if Assigned(Form) then try Form.Free except end;
if Assigned(Bitmap) then try Bitmap.Free except end;
if Assigned(Stream) then try Stream.Free except end;
if Assigned(Resultat) then try Resultat.Free except end;
end;
end;
It works very well, but it fills the transparent zones as grey and I would like them as white. Can you recommend of a way to export SVGs to bitmap while setting the transparency color or should I just loop through the bitmap changing the grey pixels to white ?.
Thank you.
CodePudding user response:
Turns out that the SVGIconImage uses the color of the parent container as the transparency color. So changing that Form.Color to my chosen TransparencyColor does the trick.
function SVG_2_Bitmap(ImageSVG: TBytes; x, y: integer; TransparencyColor: TColor = clWhite): TBytes;
var SVG: TSVGIconImage;
Stream, Resultat: TBytesStream;
Bitmap: TBitmap;
Form: TForm;
begin
SVG := nil;
Form := nil;
Stream := nil;
Bitmap := nil;
Resultat := nil;
try
Stream := TBytesStream.Create(ImageSVG);
Form := TForm.Create(nil);
Form.Color := TransparencyColor;
SVG := TSVGIconImage.Create(Form);
SVG.Parent := Form;
SVG.Proportional := True;
SVG.LoadFromStream(Stream);
SVG.Width := x;
SVG.Height := y;
Bitmap := TBitmap.Create;
Bitmap.SetSize(x, y);
SVG.PaintTo(Bitmap.Canvas, 0, 0);
Resultat := TBytesStream.Create;
Bitmap.SaveToStream(Resultat);
Result := Resultat.Bytes;
finally
try SVG.Free except end;
try Form.Free except end;
try Bitmap.Free except end;
try Stream.Free except end;
try Resultat.Free except end;
end;
end;
Thanks for all your suggestions.