Я пытаюсь создать C # Azure WebJob, которое запускается при создании нового BLOB-объекта, чтобы изменить размер загруженного изображения до трех разных размеров. Я нашел и следил за этим замечательным учебник.
Есть два раздела, первая часть «работает», но входит в цикл рекурсии, поскольку создание трех новых размеров запускает скрипт, который создает еще три экземпляра для каждого из трех новых изображений и т. Д., И т. Д. Это было сделано намеренно, чтобы подчеркнуть необходимость окончательной реализации.
Вот исходный код цикла рекурсии, который "работает" в файле Functions.cs:
public static void ResizeImagesW800([BlobTrigger("input/{name}.{ext}")] Stream input,
[Blob("output/{name}-w800.{ext}", FileAccess.Write)] Stream output)
{
ResizeImage(input, output, 800);
}
public static void ResizeImagesW500([BlobTrigger("input/{name}.{ext}")] Stream input,
[Blob("output/{name}-w500.{ext}", FileAccess.Write)] Stream output)
{
ResizeImage(input, output, 500);
}
private static void ResizeImage(Stream input, Stream output, int width)
{
var instructions = new Instructions
{
Width = width,
Mode = FitMode.Carve,
Scale = ScaleMode.Both
};
ImageBuilder.Current.Build(new ImageJob(input, output, instructions));
}
Вот код, в котором Visual Studio 2015 выдает ошибку:
public static void ResizeImagesTask(
[BlobTrigger("input/{name}.{ext}")] Stream inputBlob,
string name,
string ext,
IBinder binder)
{
int[] sizes = { 800, 500, 250 };
var inputBytes = inputBlob.CopyToBytes();
foreach (var width in sizes)
{
var input = new MemoryStream(inputBytes);
var output = binder.Bind<Stream>(new BlobAttribute($"output/{name}-w{width}.{ext}", FileAccess.Write));
ResizeImage(input, output, width);
}
}
private static void ResizeImage(Stream input, Stream output, int width)
{
var instructions = new Instructions
{
Width = width,
Mode = FitMode.Carve,
Scale = ScaleMode.Both
};
ImageBuilder.Current.Build(new ImageJob(input, output, instructions));
}
Ошибка возникает в этой строке:
var inputBytes = inputBlob.CopyToBytes();
Ошибка:
CS1061: 'Stream' does not contain a definition for 'CopyToBytes' and no extension method 'CopyToBytes' accepting a first argument of type 'Stream' could be found (are you missing a using directive or an assembly reference?)
Я пробовал использовать .NET 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1 в качестве целевых фреймворков, но все они выдают одну и ту же ошибку.
Кроме того, вот операторы using для файла Functions.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.WindowsAzure.Storage;
using ImageResizer;
Что я здесь делаю не так? Спасибо!
ОБНОВЛЕНИЕ 1
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.WindowsAzure.Storage;
using ImageResizer;
using ImageResizer.ExtensionMethods;
using Microsoft.WindowsAzure.Storage.Blob;
namespace HilcoIndustrialAssetApiWebJob
{
public class Functions
{
// output blolb sizes
private static readonly int[] Sizes = { 800, 500, 250 };
public static void ResizeImagesTask(
[QueueTrigger("newfileuploaded")] string filename,
[Blob("input/{queueTrigger}", FileAccess.Read)] Stream blobStream,
[Blob("output")] CloudBlobContainer container)
{
// Extract the filename and the file extension
var name = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
Console.WriteLine("New Blob name -> " + name);
// Get the mime type to set the content type
var mimeType = MimeMapping.GetMimeMapping(filename);
foreach (var width in Sizes)
{
// Set the position of the input stream to the beginning.
blobStream.Seek(0, SeekOrigin.Begin);
// Get the output stream
var outputStream = new MemoryStream();
ResizeImage(blobStream, outputStream, width);
// Get the blob reference
var blob = container.GetBlockBlobReference($"{name}_{width}.{ext}");
// Set the position of the output stream to the beginning.
outputStream.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(outputStream);
// Update the content type => don't know if required
blob.Properties.ContentType = mimeType;
blob.SetProperties();
}
}
private static void ResizeImage(Stream input, Stream output, int width)
{
var instructions = new Instructions
{
Width = width,
Mode = FitMode.Carve,
Scale = ScaleMode.Both
};
var imageJob = new ImageJob(input, output, instructions);
// Do not dispose the source object
imageJob.DisposeSourceObject = false;
imageJob.Build();
}
}
}