如何在WPF中将图像转换为字节数组[关闭]

问题描述 投票:0回答:1

如何在 WPF 中将图像转换为字节数组,以便与(单色)显示器(例如 Arduino 上的 OLED)一起使用。

我想要一些类似于这个网站的功能:https://javl.github.io/image2cpp/

c# wpf arduino
1个回答
0
投票

您可以从源文件创建一个 BitmapImage,然后使用 PixelFormats.BlackWhite 创建一个 FormatConvertedBitmap,并通过 CopyPixels 方法获取原始像素缓冲区。

图像转换器.cs

public static class ImageConverter
{
    public static byte[] BitmapToBlackAndWhiteByteArray(BitmapSource bitmap)
    {
        // Ensure format is Black and White (1bpp)
        FormatConvertedBitmap convertedBitmap =
            new FormatConvertedBitmap(bitmap, PixelFormats.BlackWhite, null, 0);

        int stride = (convertedBitmap.PixelWidth + 7) / 8; // bytes per row
        int height = convertedBitmap.PixelHeight;
        byte[] imageData = new byte[stride * height];

        // Copy bitmap data to byte array
        convertedBitmap.CopyPixels(imageData, stride, 0);

        return imageData;
    }
}

MainWindow.xaml

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="240" Width="240">
    <Grid>
        <Image x:Name="imageControl"/>
    </Grid>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var imagePath = @"F:\2022\CustomerCard\CustomerCard\Server\UI\CustomerCardServer\Res\Images\png\errir.png"; // Replace with your image file path
        var bitmapImage = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));

        var imageBuffer = ImageConverter.BitmapToBlackAndWhiteByteArray(bitmapImage);
        // send imageBuffer to Arduino via serial port or wifi

        var bitmapSourceMonochrome = BitmapSource.Create(
            bitmapImage.PixelWidth, bitmapImage.PixelHeight,
            bitmapImage.DpiX, bitmapImage.DpiY,
            PixelFormats.BlackWhite, null,
            imageBuffer, (bitmapImage.PixelWidth + 7) / 8);

        imageControl.Source = bitmapSourceMonochrome;
    }
}

输入

enter image description here

输出

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.