使用GDI+进行开发的一些问题(6)

问题6,多帧图像

多帧图像是指在一幅图像中有多个帧,支持多帧图像的格式不多,只有TIFF和GIF。其他格式都不能作为多帧图像存储。其中TIFF可以支持很多页,GIF动画也支持多帧。使用GDI+可以生成多帧TIFF,却没办法实现GIF动画的生成,有可能是因为专利的缘故。首先让我们来看看怎么样在生成多帧的TIFF图像。

publicvoid CreateMultiframeTIFF(string resultImage, string image1, paramsstring[] images)
{
//Read multiple frames, the frames' sizecan be different
Image frame1 = Image.FromFile(image1);
int length = images.Length;
Image[] frames = newImage[length];
for (int i = 0; i < length; i++)
{
frames[i] = Image.FromFile(images[i]);
}

//Set the first frame as the base bitmap
Bitmap bmpResult = (Bitmap)frame1;

//Create encoder parameters withdifferent values
EncoderParameters parameters = newEncoderParameters(1);
parameters.Param[0] = newEncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);

//Find Tiff codec
List<ImageCodecInfo> supportedCodecs = newList<ImageCodecInfo>();
supportedCodecs.AddRange(ImageCodecInfo.GetImageEncoders());
ImageCodecInfo tiffCodecInfo = supportedCodecs.Find(
delegate(ImageCodecInfo info)
{
return info.MimeType.Equals(
System.Net.Mime.MediaTypeNames.Image.Tiff,
StringComparison.OrdinalIgnoreCase);
}
);

//Save the first frame to a stream.
bmpResult.Save(resultImage,tiffCodecInfo, parameters);

//Save the second frame into the tiff
parameters.Param[0] = newEncoderParameter(Encoder.SaveFlag,
(long)EncoderValue.FrameDimensionPage);

foreach (Image frame in frames)
{
bmpResult.SaveAdd(frame,parameters);
}

//flush the stream

parameters.Param[0] = newEncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush);

bmpResult.SaveAdd(parameters);

//dispose all resources
frame1.Dispose();
foreach (Image frame in frames)
{
frame.Dispose();
}
bmpResult.Dispose();
}

这里我们使用了EncoderParameters来设置图像编码的参数,首先在第一帧保存的时候设置多帧属性(16,17行),然后拿到Tiff的编码器(20 - 29行)。先使用EncoderParamters 和 ImageCodecInfo对第一帧进行保存,然后使用SaveAdd方法添加新的帧。最后Flush了一下流,其实是可选的,因为在Bitmap dispose的时候会自动flush。


读取多帧TIFF比较简单,直接调用GetFrameCount和SelectActiveFrame就可以了,我们可以通过下面第一行获得所有帧数,第二行选择当前的帧。

int count = bmp.GetFrameCount(FrameDimension.Page);
bmp.SelectActiveFrame(FrameDimension.Page, 1);

GDI+可以读取GIF动画,所不同的是在上面代码1,2行中,要使用FrameDimension.Time参数传入。虽然GDI+没有现成的函数实现生成GIF动画,不过可以通过别的办法来实现。这年头没有做不到的,只有想不到的。不过那个方法过于复杂和底层了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值