Ошибка отображения изображения TIFF для DocumentViewer (WPF, C #) - PullRequest
3 голосов
/ 08 марта 2019

Привет всем, я хочу использовать элемент управления DocumentViewer для отображения многостраничных Tiffs. Код, который я написал, выглядит следующим образом ...

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Tiff_Viewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private System.Windows.Controls.Image _Image;
        private System.Windows.Documents.FixedDocument _FixedDocument;
        private System.Windows.Documents.FixedPage _FixedPage;
        private System.Windows.Documents.PageContent _PageContent;
        public MainWindow()
        {
            InitializeComponent();
        }


    private void testbutton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            this._Image = new Image();
            FileStream ImageStream = new FileStream("C:\\Users\\ttsa\\Desktop\\DocumentViewerTest\\002544-20180907.tif", FileMode.Open, FileAccess.Read, FileShare.Read);
            TiffBitmapDecoder ImageDecoder = new TiffBitmapDecoder(ImageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            //BitmapSource bitmapSource = ImageDecoder.Frames[0];
            this._Image.Source = ImageDecoder.Frames[0];
            //this._Image.Source = new BitmapImage(new Uri("C:\\Users\\ttsa\\Desktop\\DocumentViewerTest\\AAA0011A.tif", UriKind.Relative));
            this._Image.Stretch = Stretch.None;
            this._Image.Margin = new Thickness(20);

            this._FixedPage = new System.Windows.Documents.FixedPage();
            this._FixedPage.Width = 1000;
            this._FixedPage.Height = 1000;
            this._FixedPage.Children.Add(this._Image);

            this._PageContent = new System.Windows.Documents.PageContent();
            this._PageContent.Child = this._FixedPage;

            this._FixedDocument = new FixedDocument();
            this._FixedDocument.Pages.Add(this._PageContent);

            DocumentViewer.Document = this._FixedDocument;
            //DocumentViewer.LastPage();
        }
        catch (Exception fd)
        {
            System.Windows.MessageBox.Show(fd.Message);
        }
    }
}
}

------------------------------- -------------------------------- WPF-------------------------------------------

<Window x:Class="Tiff_Viewer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Tiff_Viewer"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition Height="4*"/>
    </Grid.RowDefinitions>
    <DocumentViewer Grid.Row="1" x:Name="DocumentViewer" HorizontalAlignment="Left" Margin="0,41,0,0" VerticalAlignment="Top"/>
    <Button HorizontalAlignment="left" Content="TEST" Name="testbutton" Grid.Row="0" Width="30" Click="testbutton_Click"/>
</Grid>

Я пытался взять и отобразить только одну фрейм-страницу из TIFF. Однако, когда я запускаю программу, она показывает страницу, которую я хочу, НО, когда я перемещаю курсор мыши внутри Просмотрщика документови, в частности, внутри изображения я продолжаю получать следующую ошибку:

"System.IO.FileNotFoundException:« Не удалось найти файл »C: \ Users \ ttsa \ Desktop \ TIFF_Viewer \ Tiff_Viewer \ Tiff_Viewer \ bin\ Debug \ image '.' ".

enter image description here

Я перепробовал почти все и не могу найти способ это исправить.Кто-нибудь знает что-нибудь об этом?Есть ли что-то, что я могу сделать, чтобы это исправить?Или еще кто-нибудь знает другой способ отображения многостраничного TIFF для DocumentViewer ???

Заранее спасибо !!!

1 Ответ

1 голос
/ 08 марта 2019

Я сделал копию вашего кода, и вы не единственный, за исключением. Я не знаю, почему просмотрщик документов выбрасывает исключение «Файл не найден», и если кто-то может это объяснить, это будет оценено.

Один из способов, который я нашел, чтобы решить эту проблему, это поместить поток изображения в BitmapImage перед загрузкой в ​​просмотрщик документов. Единственная проблема в том, что я не могу заставить это работать с многостраничным Tiff:

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ImageStream;
bi.EndInit();
this._Image.Source = bi;

Один из способов заставить его работать с многостраничным TIFF - это своего рода хак, вы можете просто создать файл, который запрашивает программа. Это должен быть файл с именем Image без расширения, а также структура файла Tiff. Это может быть любой tiff, но для этого я сделал копию tiff, который мы показываем в просмотрщике документов. Если файл изображения уже существует, копировать его не нужно.

string pathToTiff = @"C: \Users\developer\Desktop\temp\test.tif";

this._Image = new Image();
FileStream ImageStream = new FileStream(pathToTiff, FileMode.Open, FileAccess.Read, 
FileShare.Read);
TiffBitmapDecoder ImageDecoder = new TiffBitmapDecoder(ImageStream, 
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

this._FixedDocument = new FixedDocument();

if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Image"))
{
    File.Copy(pathToTiff, AppDomain.CurrentDomain.BaseDirectory + @"\Image", true);
}

foreach (BitmapFrame f in ImageDecoder.Frames)
{
    this._Image = new Image();
    this._Image.Source = f.Clone(); ;
    this._Image.Stretch = Stretch.None;
    this._Image.Margin = new Thickness(20);

    this._FixedPage = new System.Windows.Documents.FixedPage();
    this._FixedPage.Width = 1000;
    this._FixedPage.Height = 1000;
    this._FixedPage.Children.Add(this._Image);

    this._PageContent = new System.Windows.Documents.PageContent();
    this._PageContent.Child = this._FixedPage;
    this._FixedDocument.Pages.Add(this._PageContent);
}
documentViewer.Document = this._FixedDocument;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...