Returning Image Files From an Azure Function

Azure functions (at least HTTP triggered ones) are essentially stateless APIs and so should be able to return files as well as other output objects such as JSON. This is indeed the case and can be done by returning a FileContentResult as in the below code which returns a QR code image, the full project for this is here.


public static class GenerateQRCode
{
	[FunctionName("GenerateQRCode")]
	public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequest req, TraceWriter log, ExecutionContext context)
	{
		log.Info("GenerateQRCode received a request.");

		string data = req.Query["data"];

		if (!string.IsNullOrEmpty(data))
		{
			QRCodeGenerator qrGenerator = new QRCodeGenerator();
			QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q);
			QRCode qrCode = new QRCode(qrCodeData);

			Bitmap qrCodeImage = qrCode.GetGraphic(20);

			log.Info("QR code image returned.");
			return new FileContentResult(ImageToByteArray(qrCodeImage), "image/jpeg");
		}
		else
		{
			log.Info("No data parameter provided.");
			return new BadRequestResult();
		}
	}

	private static byte[] ImageToByteArray(Image image)
	{
		ImageConverter converter = new ImageConverter();
		return (byte[])converter.ConvertTo(image, typeof(byte[]));
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *