C#. NET Core ImageConverter - PullRequest
       42

C#. NET Core ImageConverter

1 голос
/ 13 марта 2020

Я пытаюсь использовать класс ImageConverter в моем базовом проекте ASP. NET, чтобы преобразовать Image в byte[], но я не могу найти этот класс.

Я установил пакет System.Drawing.Common , но все еще не могу его найти.

Я использую. NET Core 3.1.

Ответы [ 2 ]

0 голосов
/ 31 марта 2020

Вы можете легко преобразовать изображение в байт.

protected virtual byte[] LoadPictureFromFile(string filePath)
{
   if (!File.Exists(filePath))
       return new byte[0];

   return File.ReadAllBytes(filePath);
}

Дополнительная помощь ..

    public byte[] ResizeImage(byte[] pictureBinary,int newWidth, int newHeight)
    {
        byte[] pictureBinaryResized;
        using (var stream = new MemoryStream(pictureBinary))
        {
            Bitmap b = null;
            try
            {
                //try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
                b = new Bitmap(stream);
            }
            catch (ArgumentException exc)
            {
              // log error
            }

            if (b == null)
            {
                //bitmap could not be loaded for some reasons
                return new byte[0];
            }

            using (var destStream = new MemoryStream())
            {

                ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                {
                    Width = newWidth,
                    Height = newHeight,
                    Scale = ScaleMode.Both,
                    Quality = _mediaSettings.DefaultImageQuality
                });
                pictureBinaryResized = destStream.ToArray();
                b.Dispose();
            }
        }

        return pictureBinaryResized;
    }
0 голосов
/ 13 марта 2020

Вместо ImageConverter вы можете попытаться посмотреть на это для ускорения:

Сохранить растровое изображение в поток:

bitmap.save(stream);

Или открыть файл изображения:

FileStream stream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);

Затем просто используйте Stream2Bytes:

byte[] OO7b = Stream2Bytes(stream);

И это метод Stream2Bytes:

public byte[] Stream2Bytes(Stream stream, int chunkSize = 1024)
{
    if (stream == null)
    {
        throw new System.ArgumentException("Parameter cannot be null", "stream");
    }

    if (chunkSize < 1)
    {
        throw new System.ArgumentException("Parameter must be greater than zero", "chunkSize");
    }

    if (chunkSize > 1024 * 64)
    {
        throw new System.ArgumentException(String.Format("Parameter must be less or equal {0}", 1024 * 64), "chunkSize");
    }

    List<byte> buffers = new List<byte>();

    using (BinaryReader br = new BinaryReader(stream)
    {
        byte[] chunk = br.ReadBytes(chunkSize);

        while (chunk.Length > 0)
        {
            buffers.AddRange(chunk);
            chunk = br.ReadBytes(chunkSize);
        }
     }

     return buffers.ToArray();
}
...