Var BitMap:TBitmap;
begin
TJPEGImage(Image1.Picture.Graphic).Grayscale:=True;
Image1.Picture.SaveToFile('C:/aa.JPG');
BitMap:=TBitmap.Create;
try
With BitMap do
begin
Width:=Image1.Picture.Width;
Height:=Image1.Picture.Height;
Canvas.Draw(0,0,Image1.Picture.Graphic);
end;
TJPEGImage(Image1.Picture.Graphic).Assign(BitMap);
TJPEGImage(Image1.Picture.Graphic).CompressionQuality:=10;
TJPEGImage(Image1.Picture.Graphic).Compress;
TJPEGImage(Image1.Picture.Graphic).SaveToFile('C:/a.JPG');
finally
BitMap.Free;
end;
还有更简单的代码:
procedure TFormMain.mnuColorToGrayClick(Sender: TObject);
var
bmp : Tbitmap;
X, Y: Integer;
I, nGray ,nTemp : Byte;
ColorTable: array[0..255] of TRGBColor;
pRGB: PRGBColor;
begin
bmp := TBitmap.Create;
bmp.Assign(image1.Picture.Graphic);
for Y := 0 to Bmp.Height - 1 do
begin
pRGB := Bmp.ScanLine[Y];
for X := 0 to Bmp.Width - 1 do
begin
// nGray :=(pRGB.R+pRGB.G+pRGB.B) div 3 ; // 变灰度算法1
nGray := Round((0.30 * pRGB.R) + (0.59 * pRGB.G) + (0.11 * pRGB.B)); // 变灰度算法2
pRGB.R := nGray;
pRGB.G := nGray;
pRGB.B := nGray;
Inc(pRGB);
end;
end;
image1.Picture.Graphic.Assign(bmp);
image1.Refresh;
bmp.Free; //释放空间,其实是全局变量更快
end;