如何在 C# 中将图像转换为 i2c oled

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

我有一个 C# WPF 应用程序,我想添加选择图标或 png 并转换它的功能,以便它可以作为字符串发送到 arduino。我想在 i2c oled 屏幕上显示图像。有很多网站可以做到这一点,但我没有找到任何 C# 代码。

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

c# wpf arduino i2c
1个回答
0
投票

虽然WPF不直接支持

System.Drawing
,但我们可以 仍然通过引用程序集来使用它:

  • Solution Explorer
    中右键单击您的项目。
  • 选择
    Add
    ->
    Reference..
    。在
    .NET
    COM
    选项卡下,找到并选择
    System.Drawing
  • 单击
    OK
    添加参考。
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public class ImageConverter
{
    public byte[] ConvertImageToByteArray(string imagePath)
    {
        using (Bitmap bitmap = LoadBitmap(imagePath))
        {
            if (bitmap == null)
            {
                throw new ArgumentException("Failed to load the image.");
            }

            return ConvertBitmapToByteArray(bitmap);
        }
    }

    private Bitmap LoadBitmap(string imagePath)
    {
        Bitmap bitmap = null;
        try
        {
            using (var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
            {
                bitmap = new Bitmap(stream);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading bitmap: {ex.Message}");
        }
        return bitmap;
    }

    private byte[] ConvertBitmapToByteArray(Bitmap bitmap)
    {
        int width = bitmap.Width;
        int height = bitmap.Height;

        // Calculate total bytes needed for the monochrome image data
        int stride = (width + 7) / 8; // Number of bytes per row (rounded up)
        int totalBytes = stride * height;

        // Create byte array for the monochrome image data
        byte[] imageData = new byte[totalBytes];

        // Lock the bitmap's bits to ensure efficient memory access
        Rectangle rect = new Rectangle(0, 0, width, height);
        BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);

        try
        {
            // Copy the data from bitmap to imageData
            IntPtr ptr = bmpData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(ptr, imageData, 0, totalBytes);
        }
        finally
        {
            bitmap.UnlockBits(bmpData);
        }

        return imageData;
    }
}

如何使用?

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

        string imagePath = "image.jpg"; // Replace with your image file path
        var imageConverter = new ImageConverter();
        byte[] imageArrays = imageConverter.ConvertImageToByteArray(imagePath);

        // Now you have the byte array `imageArrays` ready to be sent to your `Arduino` via `serial communication`
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.