Skip to content

Commit 168b4f3

Browse files
committed
refactor(VModer.Core):优化 SaveAsPng 方法的异常处理和资源释放
- 为整个方法添加 try-finally块,确保在任何情况下都能释放 Image 资源
1 parent 5b9ce57 commit 168b4f3

File tree

1 file changed

+30
-24
lines changed

1 file changed

+30
-24
lines changed

VModer.Core/Services/ImageService.cs

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -209,37 +209,43 @@ private string ConvertToPng(string spriteName, string filePath, short totalFrame
209209

210210
private string SaveAsPng(string spriteName, Image image, short totalFrames, short frame)
211211
{
212-
string outputPath;
213-
if (totalFrames == 1)
214-
{
215-
outputPath = GetSingleFrameImagePath(spriteName);
216-
image.SaveAsPng(outputPath);
217-
}
218-
else
212+
try
219213
{
220-
outputPath = GetMultipleFrameImagePath(spriteName, frame);
221-
// 计算每帧宽度
222-
int frameWidth = image.Width / totalFrames;
223-
if (frameWidth * totalFrames != image.Width)
214+
string outputPath;
215+
if (totalFrames == 1)
224216
{
225-
throw new ArgumentException($"图像宽度必须能被总帧数整除,当前宽度: {image.Width}, 总帧数: {totalFrames}");
217+
outputPath = GetSingleFrameImagePath(spriteName);
218+
image.SaveAsPng(outputPath);
226219
}
227-
228-
// 遍历每一帧
229-
for (int i = 0; i < totalFrames; i++)
220+
else
230221
{
231-
// 计算裁剪区域
232-
int x = i * frameWidth;
233-
var cropRect = new Rectangle(x, 0, frameWidth, image.Height);
222+
outputPath = GetMultipleFrameImagePath(spriteName, frame);
223+
// 计算每帧宽度
224+
int frameWidth = image.Width / totalFrames;
225+
if (frameWidth * totalFrames != image.Width)
226+
{
227+
throw new ArgumentException($"图像宽度必须能被总帧数整除,当前宽度: {image.Width}, 总帧数: {totalFrames}");
228+
}
234229

235-
// 裁剪并保存
236-
using var frameImage = image.Clone(ctx => ctx.Crop(cropRect));
237-
frameImage.SaveAsPng(GetMultipleFrameImagePath(spriteName, i + 1));
230+
// 遍历每一帧
231+
for (int i = 0; i < totalFrames; i++)
232+
{
233+
// 计算裁剪区域
234+
int x = i * frameWidth;
235+
var cropRect = new Rectangle(x, 0, frameWidth, image.Height);
236+
237+
// 裁剪并保存
238+
using var frameImage = image.Clone(ctx => ctx.Crop(cropRect));
239+
frameImage.SaveAsPng(GetMultipleFrameImagePath(spriteName, i + 1));
240+
}
238241
}
239-
}
240242

241-
image.Dispose();
242-
return outputPath;
243+
return outputPath;
244+
}
245+
finally
246+
{
247+
image.Dispose();
248+
}
243249
}
244250

245251
private static Image GetImageByFormat(IImage image, byte[] newData)

0 commit comments

Comments
 (0)