BitmapMetadata位图元素据

相关类信息见下一章
clipboard.png

效果:

  1. 创建图像文件流,解码对象
  2. 获取位图帧,得到就地执行元素据编写类
  3. 编写图形描述信息到图形流中

关键词:

  1. CreateInPlaceBitmapMetadataWriter()
  2. SetQuery()
  3. BitmapCacheOption.Default
Stream pngStream = new FileStream("smiley.png", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    var pngDecoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.Default);
    var pngFrame = pngDecoder.Frames[0];
    var pngInplace = pngFrame.CreateInPlaceBitmapMetadataWriter();
    if (pngInplace.TrySave())
    {
        pngInplace.SetQuery("/Text/Description", "Have a nice day.");
    }
    pngStream.Close();

ps:必须使用 Default 或 OnDemand 缓存选项对位图进行解码。InPlaceBitmapMetadataWriter 由解码的位图帧创建。

BMPEncoderAndDecoder图像编码与解码

效果:

  1. 构造一个位图源,初始化为位图帧,添加到编码器中帧集
  2. bmp编码器保存图像源到文件存储。-----
  3. 通过文件流参数构造解码器,获取图像帧作为Image的源。
  4. 通过Uri对象参数构造解码器,同样获取图像帧作为源。
var mySv = new ScrollViewer();

    var width = 128;
    var height = width;
    var stride = width/8;
    var pixels = new byte[height*stride];

    // Try creating a new image with a custom palette.
    var colors = new List<Color>
    {
        Colors.Red,
        Colors.Blue,
        Colors.Green
    };
    var myPalette = new BitmapPalette(colors);

    // Creates a new empty image with the pre-defined palette
    var image = BitmapSource.Create(
        width,
        height,
        96,
        96,
        PixelFormats.Indexed1,
        myPalette,
        pixels,
        stride);

    var stream = new FileStream("new.bmp", FileMode.Create);
    var encoder = new BmpBitmapEncoder();
    var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author};
    encoder.Frames.Add(BitmapFrame.Create(image));
    encoder.Save(stream);

第一种解码:

// Open a Stream and decode a BMP image
    Stream imageStreamSource = new FileStream("tulipfarm.bmp", FileMode.Open, FileAccess.Read, FileShare.Read);
    var decoder = new BmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.Default);
    BitmapSource bitmapSource = decoder.Frames[0];

第二种解码:

// Open a Uri and decode a BMP image
    var myUri = new Uri("tulipfarm.bmp", UriKind.RelativeOrAbsolute);
    var decoder2 = new BmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.Default);
    BitmapSource bitmapSource2 = decoder2.Frames[0];

    // Draw the Image
    var myImage2 = new Image
    {
        Source = bitmapSource2,
        Stretch = Stretch.None,
        Margin = new Thickness(20)
    };

以上BMP、GIF、JPGE、PNG、TIFF、WDP格式解码的代码大同小异。

ImageVie图像查看器w

clipboard.png
关键词:

  1. BitmapImage(Uri)
  2. FileInfo.Length文件大小
  3. Directory.GetFiles()

关注代码:
获取当前目录的文件下的文件,获取所有文件名,构建为文件信息类实例添加ArrayList作为ListBox绑定源。

private ArrayList GetImageFileInfo()
{
    var imageFiles = new ArrayList();

    //Get directory path of myData (down two directory levels)
    var currDir = Directory.GetCurrentDirectory();
    var temp = currDir + "\\..\\..\\myData";
    var files = Directory.GetFiles(temp, "*.jpg");

    foreach (var image in files)
    {
        var info = new FileInfo(image);
        imageFiles.Add(info);
    }

    //imageFiles.Sort();

    return imageFiles;
}

private void WindowLoaded(object sender, EventArgs e)
{
    _imageFiles = GetImageFileInfo();
    imageListBox.DataContext = _imageFiles;
}

若选择一个ListBoxItem,获取选择项的uri字符串,构造为BitmapImage,作为要显示的图片源。
ps:

  1. 可直接判断选定子项是否为空,不一定需要选择项索引。
  2. 可设置SelectItemValue的值为FileInfo类型,直接进行类型转换判断。
private void ShowImage(object sender, SelectionChangedEventArgs args)
{
    var list = ((ListBox) sender);
    var index = list?.SelectedIndex; //Save the selected index 
    if (index >= 0)
    {
        var selection = list.SelectedItem.ToString();

        if (!string.IsNullOrEmpty(selection))
        {
            //Set currentImage to selected Image
            var selLoc = new Uri(selection);
            var id = new BitmapImage(selLoc);
            var currFileInfo = new FileInfo(selection);
            currentImage.Source = id;

            //Setup Info Text
            imageSize.Text = id.PixelWidth + " x " + id.PixelHeight;
            imageFormat.Text = id.Format.ToString();
            fileSize.Text = ((currFileInfo.Length + 512)/1024) + "k";
        }
    }
}

那么ListBox的子项怎么显示为图片呢?

  1. ItemContainerStyle子项容器样式中的控件模板设置有Image控件,Image绑定源设置为绑定源中的文件路径

<ListBox
        Name="imageListBox"
        Style="{StaticResource ScrollingListBox}"
        ItemContainerStyle="{StaticResource ImageListStyle}"
        ItemsSource="{Binding}"
SelectionChanged="ShowImage"
           Height="300px" />

自己设置了图片名字提示ToolTip。
子项样式设置DockPanel宽为100,

<Style x:Key="ImageListStyle">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel Width="100px" Margin="3">
                    <Image Source="{Binding Path=FullName}" >
                        <Image.ToolTip >
                            <ToolTip Content="{Binding Path=Name}"/>
                        </Image.ToolTip>
                    </Image>
                    <TextBlock Text="{Binding Path=FullName}" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

ListBox的本身样式设置有滚动条,StackPanel作为其主容器:

<StackPanel.Resources>
<Style x:Key="ScrollingListBox" TargetType="{x:Type ListBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border 
          BorderThickness ="{TemplateBinding BorderThickness}"
          BorderBrush     ="{TemplateBinding BorderBrush}">
                    <ScrollViewer Height="{TemplateBinding Height}" 
             Width="{TemplateBinding Width}">
                        <StackPanel Name="ListBoxStackPanel" IsItemsHost="true" Margin="10"/>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

以上。。。也可改进些

  1. 加入打开文件对话框,可自定义选择添加图片,
  2. 添加删除ListBox的子项功能,那么绑定源需要继承ObserveCollection<FileInfo>

李志玮
22 声望34 粉丝

求索~~


引用和评论

0 条评论