读书人

图片按比例压缩解决思路

发布时间: 2012-03-22 17:43:57 作者: rapoo

图片按比例压缩
我想在一个固定的范围打印图片,由于图片的大小不一样,出现了拉伸等现象,我想按照比例缩小图片,然后把图片写到这个固定的范围,
请问应该怎么做啊?

[解决办法]
先算出图片压缩后的width和heigth,在用CopyRect
functio GetDestRect(ABitmap:TBitmap;AWidth,AHeight:integer):TRect;
//Awidth,AHeight目的设备的长和宽
var dx:double;
begin

//如果图片不是缩小我就不考虑,lz自己写个分支把返回值居中就是了
if ABitmap.Width/AWidth> ABitmap.Height/AHeight then
dx:=AWidth/ABitmap.Width
else
dx:=Aheight/ABitmap.height
Result.left:=trunc((AWidth-dx*ABitmap.width)/2);
Result.Top:=trunc((AHeight-dx*ABitmap.height)/2);
Result.Right:=Result.Left+dx*ABitmap.width
Result.Bottom:=Result.Top+dx*ABitmap.height
end;

得到目的巨型后在把原图片CopyRect进目的巨型就行了,
[解决办法]
// Bitmap图片缩放, 仅支持pf24bit, 调用前还要先设置 bmpDest尺寸。
type
TParamRec = Record
x: integer;
B: integer;
dhB: integer;
end;
PParamRec = ^TParamRec;
var
ParamArr: array of TParamRec;
procedure Stretch_Linear(bmpDest: TBitmap; bmpSrc: TBitmap);
var
sw: integer;
sh: integer;
dw: integer;
dh: integer;
N, y: integer;
pLinePrev, pLineNext: PByte;
pDest: PByte;
pA, pB, pC, pD: PByte;
nPixelSize: integer;
i, j, k: integer;
BxN, dwXdh, dwN: integer;
dwXdh_dhB_dwN: integer;
dwXdh_shr_1: integer;
pParam: PParamRec;
begin
if (bmpDest.PixelFormat <> pf24bit)
or (bmpSrc.PixelFormat <> pf24bit) then
Exit;

sw := bmpSrc.Width - 1;
sh := bmpSrc.Height - 1;
dw := bmpDest.Width - 1;
dh := bmpDest.Height - 1;
dwXdh := dw * dh;
dwXdh_shr_1 := dwXdh shr 1;
SetLength(ParamArr, dw + 1);

nPixelSize := 3;

for i := 0 to dh do
begin

pDest := bmpDest.ScanLine[i];

y := i * sh div dh;

N := dh - i * sh mod dh;

dwN := dw * N;

pLinePrev := bmpSrc.ScanLine[y];
Inc(y);
if ( N = dh ) then
pLineNext := pLinePrev
else
pLineNext := bmpSrc.ScanLine[y];

for j := 0 to dw do
begin
pParam := @ParamArr[j];
with pParam^ do
begin
if i = 0 then
begin
x := j * sw div dw * nPixelSize;
B := dw - j * sw mod dw;
dhB := dh * B;
end;
BxN := B * N;
dwXdh_dhB_dwN := dwXdh - dhB - dwN;

pA := pLinePrev;
Inc(pA, x);

pB := pA;
Inc(pB, nPixelSize);

pC := pLineNext;
Inc(pC, x);

pD := pC;
Inc(pD, nPixelSize);

if ( B = dw ) then
begin
pB := pA;
pD := pC;
end;
for k := 0 to nPixelSize-1 do
begin
pDest^ := ( BxN * ( pA^ - pB^ - pC^ + pD^ ) + dwN * pB^
+ dhB * pC^ + ( dwXdh_dhB_dwN ) * pD^
+ dwXdh_shr_1 ) div ( dwXdh );
Inc(pA);
Inc(pB);
Inc(pC);
Inc(pD);
Inc(pDest);
end;
end;


end
end;
end;

读书人网 >.NET

热点推荐