簡體   English   中英

簡單的程序,將圖像轉換為c#中的字節數組並顯示該數組

[英]simple program to convert image to byte array in c# and display that array

這是我寫的程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {

            Image img = Image.FromFile("C:\\images.JPG");
            byte[] bArr = imgToByteArray(img);

        }
        public byte[] imgToByteArray(System.Drawing.Image Imagein)
        {
            byte[] data = null;using (System.IO.MemoryStream ms = new MemoryStream())
            {
                Imagein.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                data = ms.ToArray();

            }
            return data;
        }
    }
}

現在,當我構建程序時,它顯示錯誤

非靜態字段,方法或屬性“ Program.imgToByteArray(Image)”需要對象引用

錯誤非常明顯,您不能在靜態上下文(方法)中訪問非靜態方法。

您有兩個選擇可解決此問題。

選項1

使您的函數/方法成為靜態函數。

public static byte[] imgToByteArray(System.Drawing.Image Imagein)
{
   ...
}

選項2:

創建一個Program實例並訪問該方法。

new Program().imgToByteArray(img);

由於您要在控制台中打印字節數組(不確定為什么?),因此可以執行以下操作。

Console.WriteLine(string.Join(",", bytearray);

使imgToByteArray方法為靜態。 確實沒有其他合理的選擇。

關於@Hari Prasad答案的選項2,您認為是“可能的選擇”:您將創建一個新的類實例,以從靜態類成員中調用該實例的成員,該成員是應用程序的主要入口點,具有相當的核心作用,並且給定代碼設計指南,即https://msdn.microsoft.com/zh-cn/library/ms245046.aspx,這是您不應該做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM