Magick.Net 将 AI 转换为 PNG

本文关键字:PNG 转换 AI Net Magick | 更新日期: 2023-09-27 18:35:49

我在 Magick.NET 上遇到了一些问题。我正在尝试将从URL下载的图像转换为内存流,然后尝试将图像转换为png。我的代码执行没有任何错误,并且创建了一个文件(并上传),但由于某种原因,该文件为 0kb 并且不可读。

我的类看起来像这样:

/// <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";
    }
}
转换

方法似乎有问题,但我无法弄清楚问题是什么。有谁知道问题可能是什么?

Magick.Net 将 AI 转换为 PNG

在将内存流上传到 Azure 之前,应将内存流的位置移回开头:

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)。