Last active
July 29, 2024 10:41
-
-
Save fileformat-heic-gists/f427c19f39f949a80c09700ae2c37d5a to your computer and use it in GitHub Desktop.
Convert HEIC to JPG programatically using System.Windows.Media.Imaging.WriteableBitmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Open the HEIC file named "filename.heic" in read mode using FileStream. | |
using (var fs = new FileStream("filename.heic", FileMode.Open)) | |
{ | |
// Load the HEIC image from the file stream into a HeicImage object. | |
HeicImage image = HeicImage.Load(fs); | |
// Extract the pixel data from the HEIC image in the BGRA32 format, storing it in a byte array. | |
var pixels = image.GetByteArray(Heic.Decoder.PixelFormat.Bgra32); | |
// Retrieve the width and height of the HEIC image. | |
var width = (int)image.Width; | |
var height = (int)image.Height; | |
// Create a WriteableBitmap object with the specified width, height, DPI, pixel format, and palette. | |
var wbitmap = new WriteableBitmap(width, height, 72, 72, PixelFormats.Bgra32, null); | |
// Define a rectangle covering the entire bitmap area. | |
var rect = new Int32Rect(0, 0, width, height); | |
// Write the extracted pixel data to the WriteableBitmap object. | |
wbitmap.WritePixels(rect, pixels, 4 * width, 0); | |
// Create or open a file stream for saving the converted image as "output.jpg". | |
using FileStream saveStream = new FileStream("output.jpg", FileMode.OpenOrCreate); | |
// Create a JpegBitmapEncoder object to encode the bitmap as a JPEG image. | |
JpegBitmapEncoder encoder = new JpegBitmapEncoder(); | |
// Add the bitmap frame to the encoder. | |
encoder.Frames.Add(BitmapFrame.Create(wbitmap)); | |
// Save the encoded image to the file stream. | |
encoder.Save(saveStream); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment