路过的大虾帮看看,
以下的代码是实现:任意图片格式转成BMP图片,但为什么最后我输出的图片格式大小是0,图片格式不对?
//任意格式转BMP
function AnyToBmp(Img1:string):TBitmap; 
var
    P : TPicture ;
    bmp1:TBitmap;
begin
    try
        p:=TPicture.Create;
        p.LoadFromFile(Img1);        bmp1 := TBitmap.Create;
        bmp1.PixelFormat := pf24bit; //将图片文件转换为24格式的位图
        with bmp1 do
        begin
          Width := p.Width;
          Height := p.Height;
          Canvas.Draw(0,0,p.Graphic);
        end;
        Result:=bmp1;
    finally
        p.Free;
        bmp1.Free;
    end;
end;//调用
AnyToBmp(OpenDialog2.FileName).SaveToFile('C:\111.bmp');

解决方案 »

  1.   

    因为 函数结束后,bmp1.free释放了,返回的是个nil
    function AnyToBmp(Img1:string):TBitmap;
    var
        P : TPicture ;
        bmp1:TBitmap;
    begin
        Result:=TBitmap.Create; // <------------- 加上
        try
            p:=TPicture.Create;
            p.LoadFromFile(Img1);        bmp1 := TBitmap.Create;
            bmp1.PixelFormat := pf24bit; //将图片文件转换为24格式的位图
            with bmp1 do
            begin
              Width := p.Width;
              Height := p.Height;
              Canvas.Draw(0,0,p.Graphic);
            end;
            Result.Assign(bmp1); // <---------- bmp1复制到result
        finally
            p.Free;
            bmp1.Free;
        end;
    end;// 调用var
     bmp:TBitmap;
    begin
      bmp:=AnyToBmp(OpenDialog2.FileName);
      bmp.SaveToFile('C:\111.bmp');
      bmp.Free;
    end;
    另外注意,TPicture 并不支持所有类型的图片,所以你说的把任意图片转换,你这个函数做不到