[c#] 이미지를 바이트 배열로 변환하는 가장 빠른 방법

데스크톱 이미지를 캡처하여 압축하여 수신자에게 보내는 원격 데스크톱 공유 애플리케이션을 만들고 있습니다. 이미지를 압축하려면 byte []로 변환해야합니다.

현재 나는 이것을 사용하고 있습니다 :

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

하지만 ImageFormat으로 저장해야하고 리소스를 소모하고 (Slow Down) 다른 압축 결과를 생성 할 수 있기 때문에 마음에 들지 않습니다. 그들을 이해하십시오.

그렇다면이 목표를 달성하는 다른 방법이 있습니까?



답변

그렇다면이 목표를 달성하는 다른 방법이 있습니까?

당신이 바이트 배열로 이미지를 변환하기 위해 번호 당신이 바이트 배열로 텍스트를 변환 할 때 인코딩을 지정해야하는 것처럼 – 이미지 포맷을 지정할 수 있습니다.

압축 아티팩트가 걱정된다면 무손실 형식을 선택하세요. CPU 리소스가 걱정된다면 압축을 방해하지 않는 형식을 선택하세요. 예를 들어 원시 ARGB 픽셀 만 있습니다. 그러나 물론 그것은 더 큰 바이트 배열로 이어질 것입니다.

참고는 형식 선택하면 것을 않는 압축을 포함을하고 나중에 바이트 배열을 압축 아무 소용이 없다 -는 더 유익한 효과가없는 것은 거의 확실합니다.


답변

이미지의 파일 형식을 반환하는 Image 매개 변수의 RawFormat 속성이 있습니다. 다음을 시도 할 수 있습니다.

// extension method
public static byte[] imageToByteArray(this System.Drawing.Image image)
{
    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}


답변

Jon Skeet이 지적한 이유로 큰 이득을 얻을 수 있을지 모르겠습니다. 그러나 TypeConvert.ConvertTo 메서드를 시도하고 벤치마킹하고 현재 메서드를 사용하는 것과 비교해 볼 수 있습니다.

ImageConverter converter = new ImageConverter();
byte[] imgArray = (byte[])converter.ConvertTo(imageIn, typeof(byte[]));


답변

public static byte[] ReadImageFile(string imageLocation)
    {
        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(imageLocation);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }


답변

public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}


답변

내가 알아낼 수있는 가장 빠른 방법은 다음과 같습니다.

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

유용 할 수 있기를 바랍니다.


답변