Stream.WriteByte() not working



我正在尝试编码动画GIF。除了编写图形控制扩展块(处理动画延迟和透明度)之外,我已经设法做了所有事情。这是我当前的代码:

StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(Guid.NewGuid() + ".gif");
var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var encoder1 = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);
//FrameTimes is a list with the time of each Frame in my video file
foreach(TimeSpan ts in FrameTimes) 
{
    //Get WriteableBitmap from Frame
    List <byte[]> frames = new List <byte[]> ();
    var writableBitmap = new WriteableBitmap(frameWidth, frameHeight);
    writableBitmap.SetSource(GetFrame(ts));
    //Get stream from the WriteableBitmap
    Stream stream = writableBitmap.PixelBuffer.AsStream();
    byte[] pixels = new byte[(uint) stream.Length];
    await stream.ReadAsync(pixels, 0, pixels.Length);
    //Encode frame to GIF
    encoder1.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, frameWidth, frameHeight, 92.0, 92.0, pixels);
    //This is where it's not writing anything:
    outStream.AsStreamForWrite().WriteByte(0x21); 
    if (ts != FrameTimes.Last())
        await encoder1.GoToNextFrameAsync();
}
await encoder1.FlushAsync();
progbar.IsIndeterminate = true;
await outStream.FlushAsync();
outStream.Dispose();

所以没有写任何东西的行是outStream.AsStreamForWrite().WriteByte(0x21);。它通常是一个空,写了很多东西,但我已经确保简化的替换也不能工作,因为文件大小不会改变一个字节,有或没有这一行。你知道我犯了什么愚蠢的错误吗?

AsStreamForWrite创建了一个新的(托管的)Stream,它有自己的缓冲区。您需要适当地冲洗/关闭/处理此流。

StorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync(Guid.NewGuid() + ".gif");
var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);
var encoder1 = await BitmapEncoder.CreateAsync(BitmapEncoder.GifEncoderId, outStream);
var netOutStream = outStream.AsStreamForWrite();
foreach(TimeSpan ts in FrameTimes) 
{
  List <byte[]> frames = new List <byte[]> ();
  var writableBitmap = new WriteableBitmap(frameWidth, frameHeight);
  writableBitmap.SetSource(GetFrame(ts));
  Stream stream = writableBitmap.PixelBuffer.AsStream();
  byte[] pixels = new byte[(uint) stream.Length];
  await stream.ReadAsync(pixels, 0, pixels.Length);
  encoder1.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, frameWidth, frameHeight, 92.0, 92.0, pixels);
  netOutStream.WriteByte(0x21);
  await netOutStream.FlushAsync();
  if (ts != FrameTimes.Last())
    await encoder1.GoToNextFrameAsync();
}
await encoder1.FlushAsync();
progbar.IsIndeterminate = true;
netOutStream.Dispose();
await outStream.FlushAsync();
outStream.Dispose();

然而,我真的不确定你想做的事情是否会奏效。看起来您正在尝试将原始字节写入文件流,并且使用BitmapEncoder写入相同的流。流上的两个写入器是自找麻烦。

相关内容

  • 没有找到相关文章

最新更新