C#プログラミング、画像をバイトに変換する方法。

1.画像変換

        Bitmap bitmap = new Bitmap("D:\\桌面\\123.jpg");//获得图片



         public byte[] getImgByte(System.Drawing.Image image) //调用方法转字节

        {
            MemoryStream ms = new MemoryStream();
            try
            {
                image.Save(ms, ImageFormat.Bmp);
                byte[] bt = ms.GetBuffer();
                return bt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }

2.画像​​をBitmapImageとして読み取ります

BitmapImage ADADA = new BitmapImage(new Uri("D:\\tiptop\\桌面\\123.jpg"));

3.画像ストリーム変換

        // Bitmap --> BitmapImage
        public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);
                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }

        // BitmapImage --> Bitmap
        public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapImage));
                enc.Save(outStream);
                Bitmap bitmap = new Bitmap(outStream);
                return new Bitmap(bitmap);
            }
        }

4.画像をローカルに保存します

string filename = System.Environment.CurrentDirectory + "\\QR" + DateTime.Now.Ticks.ToString() + ".jpg";

 bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

 

 

おすすめ

転載: blog.csdn.net/qq_43307934/article/details/89400994