NEWS

[C#] Hướng dẫn chuyển đổi tập tin hình ảnh XPS sang Bitmap

[C#] Hướng dẫn chuyển đổi tập tin hình ảnh XPS sang Bitmap
Đăng bởi: Thảo Meo - Lượt xem: 2313 15:24:08, 13/07/2022DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ hướng dẫn các bạn cách chuyển đổi file ảnh XPS sang Bitmap trên C#, Winform.

[C#] How to convert XPS to Bitmap Image

Vậy tập tin XPS là gì?

File XPS hay còn gọi là XML Paper Specification (Đặc tả giấy XML mở) là dạng tài liệu mới đang được Microsoft phát triển cùng với Microsoft Silverlight, tương tự như một tệp PDF (Portable Document Format).

convert_xps_bitmap_csharp

Các bạn viết hàm cho nút chọn hình ảnh XPS:

private void btnBrowse_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "XPS Documents|*.xps" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
            txtFileName.Text = ofd.FileName;
    }
}

Tiếp đến, các bạn cần import các dll bên dưới vào project.

  1. WindowsBase.dll
  2. ReachFramework.dll
  3. PresentationFramework.dll
  4. PresentationCore.dll

Include thư viện vào project

using System;
using System.IO;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Windows.Xps.Packaging;

Đoạn code để convert file XPS to Bitmap Image C#:

public void ConvertXpsToBitmap(string fileName)
{
    using (XpsDocument xpsDocument = new XpsDocument(fileName, FileAccess.Read))
    {
        FixedDocumentSequence fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
        for (int pageCount = 0; pageCount < fixedDocumentSequence.DocumentPaginator.PageCount; ++pageCount)
        {
            DocumentPage documentPage = fixedDocumentSequence.DocumentPaginator.GetPage(pageCount);
            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)documentPage.Size.Width, (int)documentPage.Size.Height, 96, 96, System.Windows.Media.PixelFormats.Default);
            renderTarget.Render(documentPage.Visual);
            BitmapEncoder bitmapEncoder = new BmpBitmapEncoder();
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
            string file = Application.StartupPath + "\\xps_page" + pageCount + ".bmp";
            using (FileStream fileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                bitmapEncoder.Save(fileStream);
            }
        }
    }
}

Khi sử dụng, các bạn chỉ cần gọi.

private void btnConvert_Click(object sender, EventArgs e)
{
    ConvertXpsToBitmap(txtFileName.Text);
}

Thanks for watching!

Theo Foxlearn

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn chuyển đổi tập tin hình ảnh XPS sang Bitmap
Đăng bởi: Thảo Meo - Lượt xem: 2313 15:24:08, 13/07/2022DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.