이미지를 바이트 배열로 변환하는 방법
이미지를 바이트 배열로 변환하거나 바이트 배열로 변환하는 방법을 제안해 주실 수 있습니까?
WPF 어플리케이션을 개발하고 스트림 리더를 사용하고 있습니다.
이미지를 바이트 배열로 변경하는 샘플 코드
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
C# 이미지/바이트 배열 및 바이트 배열/이미지 변환기 클래스
이미지 오브젝트를 변환하는 경우byte[]다음과 같이 할 수 있습니다.
public static byte[] converterDemo(Image x)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(x, typeof(byte[]));
return xByte;
}
이미지 경로에서 바이트 배열을 가져오는 또 다른 방법은
byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
제가 현재 사용하고 있는 것은 이것입니다.제가 시도한 다른 기술 중 일부는 픽셀의 비트 깊이를 바꾸거나(24비트 대 32비트) 이미지의 해상도(dpi)를 무시했기 때문에 최적화되지 않았습니다.
// ImageConverter object used to convert byte arrays containing JPEG or PNG file images into
// Bitmap objects. This is static and only gets instantiated once.
private static readonly ImageConverter _imageConverter = new ImageConverter();
이미지에서 바이트 배열:
/// <summary>
/// Method to "convert" an Image object into a byte array, formatted in PNG file format, which
/// provides lossless compression. This can be used together with the GetImageFromByteArray()
/// method to provide a kind of serialization / deserialization.
/// </summary>
/// <param name="theImage">Image object, must be convertable to PNG format</param>
/// <returns>byte array image of a PNG file containing the image</returns>
public static byte[] CopyImageToByteArray(Image theImage)
{
using (MemoryStream memoryStream = new MemoryStream())
{
theImage.Save(memoryStream, ImageFormat.Png);
return memoryStream.ToArray();
}
}
바이트 배열에서 이미지:
/// <summary>
/// Method that uses the ImageConverter object in .Net Framework to convert a byte array,
/// presumably containing a JPEG or PNG file image, into a Bitmap object, which can also be
/// used as an Image object.
/// </summary>
/// <param name="byteArray">byte array containing JPEG or PNG file image or similar</param>
/// <returns>Bitmap object if it works, else exception is thrown</returns>
public static Bitmap GetImageFromByteArray(byte[] byteArray)
{
Bitmap bm = (Bitmap)_imageConverter.ConvertFrom(byteArray);
if (bm != null && (bm.HorizontalResolution != (int)bm.HorizontalResolution ||
bm.VerticalResolution != (int)bm.VerticalResolution))
{
// Correct a strange glitch that has been observed in the test program when converting
// from a PNG file image created by CopyImageToByteArray() - the dpi value "drifts"
// slightly away from the nominal integer value
bm.SetResolution((int)(bm.HorizontalResolution + 0.5f),
(int)(bm.VerticalResolution + 0.5f));
}
return bm;
}
편집: jpg 또는 png 파일에서 이미지를 가져오려면 File을 사용하여 파일을 바이트 배열로 읽어야 합니다.ReadAllBytes():
Bitmap newBitmap = GetImageFromByteArray(File.ReadAllBytes(fileName));
이렇게 하면 비트맵과 관련된 문제를 피할 수 있으며 소스 스트림이 열린 상태로 유지되도록 하는 문제를 해결할 수 있습니다.
이것을 시험해 보세요.
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;
}
사용할 수 있습니다.File.ReadAllBytes()바이트 배열에 파일을 읽어들이는 메서드입니다.바이트 배열을 파일에 쓰려면File.WriteAllBytes()방법.
이게 도움이 됐으면 좋겠다.
자세한 내용과 샘플 코드는 이쪽에서 찾을 수 있습니다.
스트림에서 바이트를 전송하기 위해 imageBytes를 참조하지 않으면 메서드는 아무것도 반환하지 않습니다.imageBytes = m을 참조해야 합니다.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
픽셀만 사용하시겠습니까, 아니면 전체 이미지(헤더 포함)를 바이트 배열로 사용하시겠습니까?
픽셀의 경우:를 사용합니다.CopyPixels비트맵의 메서드.예를 들어 다음과 같습니다.
var bitmap = new BitmapImage(uri);
//Pixel array
byte[] pixels = new byte[width * height * 4]; //account for stride if necessary and whether the image is 32 bit, 16 bit etc.
bitmap.CopyPixels(..size, pixels, fullStride, 0);
코드:
using System.IO;
byte[] img = File.ReadAllBytes(openFileDialog1.FileName);
모든 유형의 이미지(예: PNG, JPG, JPEG)를 바이트 배열로 변환하기 위한 코드입니다.
public static byte[] imageConversion(string imageName){
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
return imageByteArr
}
이미지를 바이트 배열로 변환합니다.코드는 다음과 같습니다.
public byte[] ImageToByteArray(System.Drawing.Image images)
{
using (var _memorystream = new MemoryStream())
{
images.Save(_memorystream ,images.RawFormat);
return _memorystream .ToArray();
}
}
바이트 배열을 이미지로 변환합니다.코드는 다음과 같습니다.코드는 핸들입니다.A Generic error occurred in GDI+를 누릅니다.
public void SaveImage(string base64String, string filepath)
{
// image convert to base64string is base64String
//File path is which path to save the image.
var bytess = Convert.FromBase64String(base64String);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
이 코드는 SQLSERVER 2012 테이블에서 처음 100개의 행을 검색하고 행당 이미지를 로컬 디스크에 파일로 저장합니다.
public void SavePicture()
{
SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("tablename");
byte[] MyData = new byte[0];
da.Fill(ds, "tablename");
DataTable table = ds.Tables["tablename"];
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow myRow;
myRow = ds.Tables["tablename"].Rows[i];
MyData = (byte[])myRow["Picture"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);
FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();
}
}
주의:새 폴더 이름을 가진 디렉토리가 C:\에 있어야 합니다.
언급URL : https://stackoverflow.com/questions/3801275/how-to-convert-image-to-byte-array
'programing' 카테고리의 다른 글
| Nullable, __nullable 및 _Nullable in Objective-C의 Nullable의 차이 (0) | 2023.04.14 |
|---|---|
| Windows에서 pip install 액세스가 거부되었습니다. (0) | 2023.04.09 |
| PostgreSQL에서 활성 연결을 나열하는 방법 (0) | 2023.04.09 |
| 메서드 호출을 1초간 지연하려면 어떻게 해야 합니까? (0) | 2023.04.09 |
| git에게 자기 서명 증명서를 받아들이게 하려면 어떻게 해야 합니까? (0) | 2023.04.09 |