Skip to content

Commit 9635b83

Browse files
committed
refactor: more safe code to decode image resources
Signed-off-by: leo <longshuang@msn.cn>
1 parent 823bde3 commit 9635b83

1 file changed

Lines changed: 21 additions & 9 deletions

File tree

src/ViewModels/ImageSource.cs

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,23 @@ private static ImageSource DecodeWithPfim(Stream stream, long size)
164164
return new ImageSource(null, 0);
165165
}
166166

167-
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(data, 0);
168-
var pixelSize = new PixelSize(pfiImage.Width, pfiImage.Height);
169-
var dpi = new Vector(96, 96);
170-
var bitmap = new Bitmap(pixelFormat, alphaFormat, ptr, pixelSize, dpi, stride);
171-
return new ImageSource(bitmap, size);
167+
var handle = GCHandle.Alloc(data, GCHandleType.Pinned);
168+
try
169+
{
170+
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(data, 0);
171+
var pixelSize = new PixelSize(pfiImage.Width, pfiImage.Height);
172+
var dpi = new Vector(96, 96);
173+
var bitmap = new Bitmap(pixelFormat, alphaFormat, ptr, pixelSize, dpi, stride);
174+
return new ImageSource(bitmap, size);
175+
}
176+
catch
177+
{
178+
return new ImageSource(null, 0);
179+
}
180+
finally
181+
{
182+
handle.Free();
183+
}
172184
}
173185
}
174186

@@ -198,14 +210,14 @@ private static ImageSource DecodeWithTiff(Stream stream, long size)
198210
private static ImageSource DecodeWithStbImage(Stream stream, long size)
199211
{
200212
var image = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha);
201-
202213
var data = image.Data;
203214
var stride = image.Width * (int)image.Comp;
204-
205-
var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(data, 0);
206215
var pixelSize = new PixelSize(image.Width, image.Height);
207216
var dpi = new Vector(96, 96);
208-
var bitmap = new Bitmap(PixelFormat.Rgba8888, AlphaFormat.Unpremul, ptr, pixelSize, dpi, stride);
217+
var bitmap = new WriteableBitmap(pixelSize, dpi, PixelFormats.Rgba8888, AlphaFormat.Unpremul);
218+
219+
using var frameBuffer = bitmap.Lock();
220+
Marshal.Copy(data, 0, frameBuffer.Address, data.Length);
209221
return new ImageSource(bitmap, size);
210222
}
211223
}

0 commit comments

Comments
 (0)