ASP.. NET在ashx处理程序中保存图像

本文关键字:保存 图像 程序 处理 NET ashx ASP | 更新日期: 2023-09-27 18:01:18

我有一个简单的处理程序(ASHX),它接收base 64编码的图像,我想保存该图像。

代码如下:

 Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim imageInfo = context.Request("imgData")
    Dim imageData As String() = imageInfo.Split(",")
    ' check that there are two parts; ie the header and the string data.
    If imageData.Length < 2 Then
        context.Response.Write("error")
        Return
    End If
    ' Example of imageInfo
    ' data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE...
    Dim imageType As String = imageData(0)
    Dim imageString As String = imageData(1)
    If imageType <> "data:image/png;base64" Then
        context.Response.Write("error")
        Return
    End If
    imageString = imageString.Replace(" ", "+")
    Dim bytes As Byte()
    bytes = Convert.FromBase64String(imageString)
    Dim image As System.Drawing.Image
    Using ms As MemoryStream = New MemoryStream(bytes)
        image = System.Drawing.Image.FromStream(ms)
    End Using
    image.Save("test", System.Drawing.Imaging.ImageFormat.Png)
End Sub

但是,我得到以下错误:

类型的异常"System.Runtime.InteropServices。ExternalException'发生在System.Drawing.dll,但未在用户代码

中处理

附加信息:在GDI+

中发生了一个通用错误

我知道图像数据很好,因为它在php版本中工作。我正在尝试将PHP转换为ASP.NET。

/*get file name and image data from POST*/
$filename = $_POST['filename'];
$data = $_POST['imgdata'];
list( $type, $data ) = explode( ';', $data );
list( $base, $data ) = explode( ',', $data );
/*check that image data is base64 of png*/
if ( $type === 'data:image/png' && $base === 'base64') {
    $data = base64_decode( $data );
    file_put_contents( '../pathtosave/' . $filename, $data );
    echo 'saved';
} else {
    echo 'error';
}

在调试器中检查图像,看起来没有问题。它正确地获取图像的高度和宽度。

有人能看到错误可能在哪里吗?

ASP.. NET在ashx处理程序中保存图像

我好尴尬。问题是"test"不是正确的文件路径。我正在我的本地机器上进行测试,一旦我使用了完整的路径,它就会立即工作。