C# 如何在同一个aspx页面中临时存储一个映像,而不使用文件系统?

C# 如何在同一个aspx页面中临时存储一个映像,而不使用文件系统?,c#,asp.net,jcrop,C#,Asp.net,Jcrop,我正在使用asp.net webforms和jcrop(文件上传后裁剪图像) 我在这里的这个示例将临时映像存储到文件系统中,但是。。由于azure的原因,我不能(也不会)这样做 苏。。如果不保存到磁盘,如何具有相同的功能?这意味着。。。如果可能的话,我想让一条小溪穿过这条线 public partial class UserConfig : System.Web.UI.Page { String path = HttpContext.Current.Request.PhysicalApp

我正在使用asp.net webforms和jcrop(文件上传后裁剪图像)

我在这里的这个示例将临时映像存储到文件系统中,但是。。由于azure的原因,我不能(也不会)这样做

苏。。如果不保存到磁盘,如何具有相同的功能?这意味着。。。如果可能的话,我想让一条小溪穿过这条线

public partial class UserConfig : System.Web.UI.Page
{
    String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Boolean FileOK = false;
        Boolean FileSaved = false;

        if (Upload.HasFile)
        {
            Session["WorkingImage"] = Upload.FileName;
            String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
            String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (FileExtension == allowedExtensions[i])
                {
                    FileOK = true;
                }
            }
        }

        if (FileOK)
        {
            try
            {
                Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                FileSaved = true;
            }
            catch (Exception ex)
            {
                lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                lblError.Visible = true;
                FileSaved = false;
            }
        }
        else
        {
            lblError.Text = "Cannot accept files of this type.";
            lblError.Visible = true;
        }

        if (FileSaved)
        {
            pnlUpload.Visible = false;
            pnlCrop.Visible = true;
            imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
        }
    }

    protected void btnCrop_Click(object sender, EventArgs e)
    {
        string ImageName = Session["WorkingImage"].ToString();
        int w = Convert.ToInt32(W.Value);
        int h = Convert.ToInt32(H.Value);
        int x = Convert.ToInt32(X.Value);
        int y = Convert.ToInt32(Y.Value);

        byte[] CropImage = Crop(path + ImageName, w, h, x, y);
        using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
        {
            ms.Write(CropImage, 0, CropImage.Length);
            using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
            {
                string SaveTo = path + "crop" + ImageName;
                CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                pnlCrop.Visible = false;
                pnlCropped.Visible = true;
                imgCropped.ImageUrl = "images/crop" + ImageName;
            }
        }
    }

    static byte[] Crop(string Img, int Width, int Height, int X, int Y)
    {
        try
        {
            using (SD.Image OriginalImage = SD.Image.FromFile(Img))
            {
                using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
                {
                    bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                    using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);
                        MemoryStream ms = new MemoryStream();
                        bmp.Save(ms, OriginalImage.RawFormat);
                        return ms.GetBuffer();
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            throw (Ex);
        }
    }

}
public部分类UserConfig:System.Web.UI.Page
{
字符串路径=HttpContext.Current.Request.PhysicalApplicationPath+“images\\”;
受保护的无效页面加载(对象发送方、事件参数e)
{
}
受保护的void btnUpload\u单击(对象发送方,事件参数e)
{
布尔FileOK=false;
布尔FileSaved=false;
if(Upload.HasFile)
{
会话[“WorkingImage”]=Upload.FileName;
String FileExtension=Path.GetExtension(会话[“WorkingImage”].ToString()).ToLower();
字符串[]allowedExtensions={.png“,.jpeg“,.jpg“,.gif”};
for(int i=0;i
如果您不反对使用Azure存储,下面是我使用的一个类。它是专为上传图像和PDF而设计的,但我相信您可以修改它以满足您的需要

用法:

Dim storage As AzureStorage = New AzureStorage("storage name", "storage key")
    storage.UploadFile("directory name", "filename", fileStream)
上传后,可通过url访问您的文件:

http://yourdomain.blob.core.windows.net/container-name/filename
助手类:

Imports System
Imports System.IO

Imports Microsoft.WindowsAzure.Storage
Imports Microsoft.WindowsAzure.Storage.Auth
Imports Microsoft.WindowsAzure.Storage.Blob


'
'   See http://msdn.microsoft.com/en-us/library/dd135715.aspx for naming guidelines.
'

Public Class AzureStorage

    Public Sub New(ByVal storageName As String, ByVal storageKey As String)

        Me.StorageName = storageName
        Me.StorageKey = storageKey

    End Sub



    Private Function GetStorageAccount() As CloudStorageAccount

        Dim result As CloudStorageAccount = New CloudStorageAccount(New StorageCredentials(StorageName, StorageKey), True)

        Return result

    End Function



    Private Function GetBlobContainer(ByVal name As String) As CloudBlobContainer

        Dim account As CloudStorageAccount = GetStorageAccount()
        Dim client As CloudBlobClient = account.CreateCloudBlobClient
        Dim result As CloudBlobContainer = client.GetContainerReference(name)

        result.CreateIfNotExists(BlobContainerPublicAccessType.Blob)

        Return result

    End Function



    Private Function GetBlob(ByVal containerName As String, ByVal name As String) As CloudBlockBlob

        Dim container As CloudBlobContainer = GetBlobContainer(containerName)
        Dim result As CloudBlockBlob = container.GetBlockBlobReference(name)

        Return result

    End Function



    Public Sub UploadFlyer(ByVal fileName As String, ByVal stream As Stream)

        UploadFile("flyers", fileName, stream)

    End Sub



    Public Sub UploadLogo(ByVal fileName As String, ByVal stream As Stream)

        UploadFile("class-logos", fileName, stream)

    End Sub



    Public Sub UploadFile(ByVal containerName As String, ByVal fileName As String, ByVal stream As Stream)

        Dim blob As CloudBlockBlob = GetBlob(containerName, fileName)
        Dim targetMaximumSize As Int32 = 144
        Dim width As Int32 = targetMaximumSize
        Dim height As Int32 = targetMaximumSize
        Dim coefficient As Decimal = 1
        Dim imageStream As Stream = New MemoryStream

        Dim formats As Dictionary(Of String, System.Drawing.Imaging.ImageFormat) = New Dictionary(Of String, Drawing.Imaging.ImageFormat)
        Dim extension As String = Path.GetExtension(fileName).Trim.ToLower

        formats.Add(".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
        formats.Add(".png", System.Drawing.Imaging.ImageFormat.Png)

        '
        '   Resize source image to max 144px (2") to a side
        '
        If formats.ContainsKey(extension) Then
            Using sourceImage As System.Drawing.Image = System.Drawing.Image.FromStream(stream)
                coefficient = targetMaximumSize / Math.Max(sourceImage.Width, sourceImage.Height)
                If coefficient < 1 Then
                    width = sourceImage.Width * coefficient
                    height = sourceImage.Height * coefficient
                    Using targetImage As System.Drawing.Image = New System.Drawing.Bitmap(width, height)
                        Using graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(targetImage)
                            graphics.DrawImage(sourceImage, targetImage.GetBounds(System.Drawing.GraphicsUnit.Pixel), sourceImage.GetBounds(System.Drawing.GraphicsUnit.Pixel), Drawing.GraphicsUnit.Pixel)
                        End Using
                        targetImage.Save(imageStream, formats(extension))
                    End Using
                Else
                    sourceImage.Save(imageStream, formats(extension))
                End If
            End Using

            imageStream.Seek(0, SeekOrigin.Begin)
            blob.UploadFromStream(imageStream)
        Else
            blob.UploadFromStream(stream)
        End If
        imageStream.Dispose()

    End Sub



    Public Sub DeleteFile(ByVal containerName As String, ByVal fileName As String)

        Dim blob As CloudBlockBlob = GetBlob(containerName, fileName)

        blob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots)

    End Sub



    Public Property StorageName As String = String.Empty

    Public Property StorageKey As String = String.Empty

End Class
导入系统
导入System.IO
导入Microsoft.WindowsAzure.Storage
导入Microsoft.WindowsAzure.Storage.Auth
导入Microsoft.WindowsAzure.Storage.Blob
'
”“看到了吗http://msdn.microsoft.com/en-us/library/dd135715.aspx 用于命名指南。
'
公共级AzureStorage
Public Sub New(ByVal storageName作为字符串,ByVal storageKey作为字符串)
Me.StorageName=StorageName
Me.StorageKey=StorageKey
端接头
私有函数GetStorageAccount()作为CloudStorageAccount
Dim结果为CloudStorageAccount=New CloudStorageAccount(New StorageCredentials(StorageName,StorageKey),True)
返回结果
端函数
私有函数GetBlobContainer(ByVal名称作为字符串)作为CloudBlobContainer
作为CloudStorageAccount=GetStorageAccount()的Dim帐户
Dim客户端作为CloudBlobClient=account.CreateCloudBlobClient
Dim结果为CloudBlobContainer=client.GetContainerReference(名称)
result.CreateIfNotExists(BlobContainerPublicAccessType.Blob)
返回结果
端函数
私有函数GetBlob(ByVal containerName作为字符串,ByVal name作为字符串)作为CloudBlockBlob
将容器设置为CloudBlobContainer=GetBlobContainer(containerName)
Dim结果为CloudBlockBlob=container.GetBlockBlobReference(名称)
返回结果
端函数
公共子上传传单(ByVal文件名为字符串,ByVal流为流)
上传文件(“传单”、文件名、流)
端接头
公共子上传徽标(ByVal文件名为字符串,ByVal流为流)