2016-02-23 3 views
0

У меня возникли проблемы с Magick.NET. Я пытаюсь преобразовать изображение, которое я загружаю из URL-адреса в поток памяти, тогда я пытаюсь преобразовать изображение в png. Мой код выполняется без ошибок, и файл создается (и загружается), но по какой-то причине файл 0kb и нечитабелен.Magick.Net преобразование ai в png

Мой класс выглядит следующим образом:

/// <summary> 
/// Used to help with image control 
/// </summary> 
public class ImageProvider 
{ 

    // Private property for the azure container 
    private readonly CloudBlobContainer container; 

    /// <summary> 
    /// Default constructor 
    /// </summary> 
    public ImageProvider() 
    { 

     // Get our absolute path to our ghostscript files 
     var path = HostingEnvironment.MapPath("~/App_Data/Ghostscript"); 

     // Set our ghostscript directory 
     MagickNET.SetGhostscriptDirectory(path); 

     // Assign our container to our controller 
     var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorage"].ConnectionString); 
     var blocClient = storageAccount.CreateCloudBlobClient(); 
     this.container = blocClient.GetContainerReference("kudos-sports"); 

     // Create the container if it doesn't already exist 
     container.CreateIfNotExists(); 

     // Give public access to the blobs 
     container.SetPermissions(new BlobContainerPermissions 
     { 
      PublicAccess = BlobContainerPublicAccessType.Blob 
     }); 
    } 

    /// <summary> 
    /// Uploads an image to the azure storage container 
    /// </summary> 
    /// <param name="provider">The multipart memorystream provider</param> 
    /// <returns></returns> 
    public async Task<string> UploadImageAsync(MultipartMemoryStreamProvider provider) 
    { 

     // Read our content 
     using (var content = provider.Contents.FirstOrDefault()) 
     { 

      // If the content is empty, throw an error 
      if (content == null) 
       throw new Exception("The file was not found."); 

      // Create a new blob block to hold our image 
      var extension = this.GetFileExtension(content); 
      var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + extension); 

      // Upload to azure 
      var stream = await content.ReadAsStreamAsync(); 
      await blockBlob.UploadFromStreamAsync(stream); 

      // Return the blobs url 
      return blockBlob.StorageUri.PrimaryUri.ToString(); 
     } 
    } 

    public async Task<string> ConvertImage(string path) 
    { 

     // Create our web client 
     using (var client = new WebClient()) 
     { 

      // Get our data as bytes 
      var data = client.DownloadData(path); 

      // Create our image 
      using (var image = new MagickImage(data)) 
      { 

       // Create a new memory stream 
       using (var memoryStream = new MemoryStream()) 
       { 

        // Set to a png 
        image.Format = MagickFormat.Png; 
        image.Write(memoryStream); 

        // Create a new blob block to hold our image 
        var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + ".png"); 

        // Upload to azure 
        await blockBlob.UploadFromStreamAsync(memoryStream); 

        // Return the blobs url 
        return blockBlob.StorageUri.PrimaryUri.ToString(); 
       } 
      } 
     } 
    } 

    /// <summary> 
    /// Deletes and image from the azure storage container 
    /// </summary> 
    /// <param name="name">The name of the file to delete</param> 
    public void DeleteImage(string name) 
    { 

     // Get our item 
     var blockBlob = container.GetBlockBlobReference(name); 

     // Delete the item 
     blockBlob.Delete(); 
    } 

    /// <summary> 
    /// Gets the extension from a file 
    /// </summary> 
    /// <param name="content">The HttpContent of an uploaded file</param> 
    /// <returns></returns> 
    private string GetFileExtension(HttpContent content) 
    { 

     // Get our filename 
     var filename = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty); 

     // Split our filename 
     var parts = filename.Split('.'); 

     // If we have any parts 
     if (parts.Length > 0) 
     { 

      // Get our last part 
      var extension = parts[parts.Length - 1]; 

      // Return our extension 
      return "." + extension; 
     } 

     // If we don't have an extension, mark as png 
     return ".png"; 
    } 
} 

Это Преобразовать метод, который, кажется, есть проблемы, но я не могу понять, в чем проблема. Кто-нибудь знает, в чем проблема?

ответ

3

Вы должны переместить позицию потока памяти обратно в начале, прежде чем загрузить его в лазури:

image.Write(memoryStream); 

// Create a new blob block to hold our image 
var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + ".png"); 

// Upload to azure 
memoryStream.Position = 0; 
await blockBlob.UploadFromStreamAsync(memoryStream); 

P.S. Имейте в виду, что вам нужна лицензия на Ghostscript, если вы хотите использовать ее в коммерческом продукте (http://ghostscript.com/doc/9.16/Commprod.htm).

Смежные вопросы