簡體   English   中英

在 C# 中,如何將 Base64 字符串轉換為圖像,然后旋轉它?

[英]In C#, how can I convert a Base64 string into an Image, then rotate it?

我在 Base64 中保存了橫向和縱向混合的圖像。 我想將它們全部顯示為風景。

我能夠將 Base64 字符串轉換為 BitmapImages,然后將其設置為 Image.Source,但我無法使旋轉工作。

在這個類中,我從 XML 獲取 base64,然后調用 SetupImage,它設置 System.Windows.Controls.Image 對象的源。

我已經嘗試了兩種旋轉圖像的方法(當寬度小於高度時)都在這段代碼中。 當我在 BitmapImage 上使用 Rotation 時,對顯示的圖像沒有影響。 當我在圖像上使用 RotateTransform 時,圖像根本不顯示。

public class TrayImage
{
    [XmlAttribute("id")]
    public string ID { get; set; }
    [XmlAttribute("data")]
    public string Data { get; set; }

    /// <summary>
    /// Create an Image from the Base64 Data
    /// </summary>
    internal void SetupImage(ref System.Windows.Controls.Image image)
    {
        if (this.Data != null)
        {
            // Convert the Base64 to a BitmapImage
            byte[] _BinaryData = Convert.FromBase64String(this.Data);

            BitmapImage _ImageBitmap = new BitmapImage();
            _ImageBitmap.BeginInit();
            _ImageBitmap.StreamSource = new MemoryStream(_BinaryData);
            _ImageBitmap.EndInit();

            // If the image is portrait, rotate it
            if (_ImageBitmap.Width < _ImageBitmap.Height)
            {
                // only use one rotation method at a time!!
                //_ImageBitmap.Rotation = Rotation.Rotate90;
            }

            image.Source = _ImageBitmap;

            // If the image is portrait, rotate it
            if( image.Source.Width < image.Source.Height)
            {
                // only use one rotation method at a time!!
                RotateTransform _RotateTransform = new RotateTransform(90);
                image.RenderTransform = _RotateTransform;
            }
        }
    }
}

我應該使用其他東西來轉換,然后旋轉圖像嗎?

像這樣:這只是為了說明代碼未測試!

public static class ImageHelpers
{
    punlic byte[] ConvertFromBase64(btye[] data)
    {
        return Convert.FromBase64String(data)
    }

    public  Image Rotate90FromData(byte[] data)
    {
        Image image = null;
        if (data != null)
        {             
            BitmapImage _ImageBitmap = new BitmapImage();
            _ImageBitmap.BeginInit();
            _ImageBitmap.StreamSource = new MemoryStream(data);
            _ImageBitmap.EndInit();

            image.Source = _ImageBitmap;

            // If the image is portrait, rotate it
            if( image.Source.Width < image.Source.Height)
            {
                RotateTransform _RotateTransform = new RotateTransform(90);
                image.RenderTransform = _RotateTransform;
            }
        }
        return Image;
    }
}

public class Main
{
    public void Start()
    {
        var data64 = ImageHelpers.ConvertFromBase64(somevar);
        Image rotatedImage = ImageHelpers.Rotate90FromData(data64);

    }
}

在梳理了這里的建議以及其他問題后,我想出了一個可行的解決方案。

這些是我的“用途”

using System;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Media.Imaging;
using System.Drawing;

這是我的全班

public class TrayImage
{
    [XmlAttribute("id")]
    public string ID { get; set; }
    [XmlAttribute("data")]
    public string Data { get; set; }

    /// <summary>
    /// Create an Image from the Base64 Data
    /// </summary>
    internal System.Windows.Controls.Image SetupImage()
    {
        System.Windows.Controls.Image _Image = new System.Windows.Controls.Image();

        if (this.Data != null)
        {
            BitmapImage _BitmapImage = this.CreateBitmapImage();
            Bitmap _Bitmap = this.BitmapImage2Bitmap(_BitmapImage);

            // If the image is portrait, rotate it
            if (_Bitmap.Width < _Bitmap.Height)
            {
                _Bitmap = this.RotateImage(_Bitmap, 90);
            }

            _Image.Source = this.BitmapToBitmapImage(_Bitmap);
        }

        return _Image;
    }

    /// <summary>
    /// Convert a Bitmap into a BitmapImage
    /// </summary>
    private BitmapImage BitmapToBitmapImage(Bitmap bitmap)
    {
        using (MemoryStream _MemoryStream = new MemoryStream())
        {
            bitmap.Save(_MemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            _MemoryStream.Position = 0;
            BitmapImage _BitmapImage = new BitmapImage();
            _BitmapImage.BeginInit();
            _BitmapImage.StreamSource = _MemoryStream;
            _BitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            _BitmapImage.EndInit();

            return _BitmapImage;
        }
    }

    /// <summary>
    /// Convert a Base64 String into a BitmapImage
    /// </summary>
    private BitmapImage CreateBitmapImage()
    {
        byte[] _BinaryData = Convert.FromBase64String(this.Data);

        BitmapImage _ImageBitmap = new BitmapImage();
        _ImageBitmap.BeginInit();
        _ImageBitmap.StreamSource = new MemoryStream(_BinaryData);
        _ImageBitmap.EndInit();

        return _ImageBitmap;
    }

    /// <summary>
    /// Convert a BitmapImage into a Bitmap
    /// </summary>
    private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
    {
        using (MemoryStream _OutStream = new MemoryStream())
        {
            BitmapEncoder _Encoder = new BmpBitmapEncoder();
            _Encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
            _Encoder.Save(_OutStream);
            System.Drawing.Bitmap _Bitmap = new System.Drawing.Bitmap(_OutStream);

            return new Bitmap(_Bitmap);
        }
    }

    /// <summary>
    /// Rotate a Bitmap
    /// </summary
    private Bitmap RotateImage(Bitmap bitmap, float angle)
    {
        int _Width = bitmap.Width;
        int _Height = bitmap.Height;
        float _MoveX = (float)_Height / 2;

        // Create bitmap with Height / Width revered
        Bitmap _ReturnBitmap = new Bitmap(_Height, _Width);

        // Make a graphics object from the empty bitmap
        using (Graphics _Graphics = Graphics.FromImage(_ReturnBitmap))
        {
            // Move image along x axis
            _Graphics.TranslateTransform(_MoveX, 0);

            // Rotate image
            _Graphics.RotateTransform(angle);

            // Move image back along x axis
            // NB, now it's been rotated, the x and y axis have swapped from our perspective.
            _Graphics.TranslateTransform(0, -_MoveX);

            // Draw passed in image onto graphics object
            _Graphics.DrawImage(bitmap, new Point(0, 0));
        }
        return _ReturnBitmap;
    }
}

我是這樣做的:

using System.IO;    
using System.Drawing;

public Bitmap RotateBase64Image(string base64Image)
{
     Bitmap result = null;
     try
     {
          if (!string.IsNullOrEmpty(base64Image))
          {
              //Check if base64 string has a header
              if (base64Image.IndexOf("base64") >= 0 && base64Image.IndexOf(",") > 0)
              {
                  //get image data and exclude header
                  base64Image = base64Image.Split(',')[1];
              }
              using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64Image)))
              {
                  using (Bitmap bitmap = new Bitmap(ms))
                  {
                      //rotate 90 degree clockwise with no flip
                      bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
                      //rotate 180 degree clockwise with no flip
                      bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
                      //rotate 270 degree clockwise with no flip
                      bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                      //Flip Image horizontally with out any rotation
                      bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX);
                      //Flip Image vertically with out any rotation
                      bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

                      result = (Bitmap)bitmap.Clone();                            
                }
            }
        }
    }
    catch { }

    return result;
}

而且,如果您再次需要結果為 base64:

public string ConvertBitmapToBase64(Bitmap image)
{
    string result = "";
    try
    {
        using (MemoryStream ms2 = new MemoryStream())
        {
            image.Save(ms2, System.Drawing.Imaging.ImageFormat.Png);
            return Convert.ToBase64String(ms2.ToArray());

            //If you need the result with header
            //return "data:image/png;base64," + Convert.ToBase64String(ms2.ToArray());
        }
    }
    catch { }

    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM