我正在用UWP javascript编写一个应用程序,用于裁剪图像的侧面,裁剪掉png中透明的最左边和最右边的像素。
我编写了一个函数,可以正确读取字节并找到图像的左边界和右边界-例如,如果第一个非透明像素位于100像素,而最后一个非透明像素位于-transparent为200像素,它返回的对象看起来像{leftBound: 100, rightBound: 200, height: 50, width: 300}
。
所以我的问题是保存带有这些界限的新图像。我可以找到的唯一示例代码是this code in c#。所以我尝试遵循它,就像这样:
async function processImage(stream) {
const calcBounds = await getPixelBounds(stream.cloneStream());
const transform = new Windows.Graphics.Imaging.BitmapTransform();
transform.bounds.x = calcBounds.leftBound;
transform.bounds.width = calcBounds.rightBound - calcBounds.leftBound;
transform.bounds.height = calcBounds.height;
transform.scaledHeight = transform.bounds.height;
transform.scaledWidth = transform.bounds.width;
const decoder = await Windows.Graphics.Imaging.BitmapDecoder.createAsync(stream);
const pixelFormat = decoder.bitmapPixelFormat;
const alphaMode = decoder.bitmapAlphaMode;
const dpiX = decoder.dpiX;
const dpiY = decoder.dpiY;
const data = await decoder.getPixelDataAsync(
pixelFormat,
alphaMode,
transform,
Windows.Graphics.Imaging.ExifOrientationMode.respectExifOrientation,
Windows.Graphics.Imaging.ColorManagementMode.colorManageToSRgb
);
const pixels = data.detachPixelData();
const outputFilename = "cropped.png";
const encoderId = Windows.Graphics.Imaging.BitmapEncoder.pngEncoderId;
const folder = Windows.Storage.ApplicationData.current.localFolder;
const outputFile =
await folder.createFileAsync(outputFilename,
Windows.Storage.CreationCollisionOption.openIfExists);
const outputStream = await outputFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
outputStream.size = 0;
const encoder = await Windows.Graphics.Imaging.BitmapEncoder.createAsync(encoderId, outputStream);
encoder.setPixelData(
pixelFormat,
alphaMode,
calcBounds.rightBound - calcBounds.leftBound,
calcBounds.height,
dpiX,
dpiY,
pixels
);
await encoder.flushAsync();
stream && stream.close();
outputStream && outputStream.close();
}
调试时,我注意到的第一件事是transform.bounds
的属性没有更改。实际上,我非常确定这是我的主要问题,如果我弄清楚如何设置transform.bounds
,整个代码可能会得到解决。
我尝试仅制作一个新对象transform.bounds = {x:0, y:0, width: 0, height: 0}
,然后像稍后在代码中一样重置宽度和高度,但这没用。
在c#示例中,它使用new Windows.Graphics.Imaging.BitmapBounds()
,但在javascript中不存在...
[编辑] 我尝试过:
const transform = new Windows.Graphics.Imaging.BitmapTransform();
const bounds = { x: 0, y: 0, width: 0, height: 0 };
bounds.x = calcBounds.leftBound;
bounds.width = calcBounds.rightBound - calcBounds.leftBound;
bounds.height = calcBounds.height;
transform.bounds = bounds;
但这会在我做的行中引起异常,const data = await decoder.getPixelDataAsync(...
说参数不正确