简体   繁体   English

简单的程序,将图像转换为c#中的字节数组并显示该数组

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

here is my program that i have written 这是我写的程序

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;
        }
    }
}

now when i build the program it shows error 现在,当我构建程序时,它显示错误

an object reference is required for the non static field, method or property 'Program.imgToByteArray(Image)' 非静态字段,方法或属性“ Program.imgToByteArray(Image)”需要对象引用

The error is pretty clear, you can't access non static methods in a static context (method). 错误非常明显,您不能在静态上下文(方法)中访问非静态方法。

You have two options to fix this issue. 您有两个选择可解决此问题。

Option 1 选项1

Make your function/method a static function. 使您的函数/方法成为静态函数。

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

Option 2: 选项2:

Create an instance of Program and access the method. 创建一个Program实例并访问该方法。

new Program().imgToByteArray(img);

Since you want to print byte array in console (not sure why?) you could do something like this. 由于您要在控制台中打印字节数组(不确定为什么?),因此可以执行以下操作。

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

Make the imgToByteArray method static. 使imgToByteArray方法为静态。 There is really no other rational option. 确实没有其他合理的选择。

Regarding Option 2 from @Hari Prasad answer you considered an "possible option": You would be creating new class instance to call a member of this instance from a static class member that is the main entry point of the application which is pretty hardcore and given the code design guildelines ie https://msdn.microsoft.com/en-us/library/ms245046.aspx it is something you shouldn't. 关于@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