PNG를 저장하려고 할 때 GDI+ 에서이 일반적이고 비 설명 오류가 발생하는 이유는 무엇입니까?

StackOverflow https://stackoverflow.com/questions/511579

  •  21-08-2019
  •  | 
  •  

문제

사전 지정된 지점의 이미지에 텍스트를 동적으로 추가하는 함수가 있습니다. 원래 나는 JPEGS와 함께 그것을했는데 작동하고있었습니다. 원래 JPEG가 일종의 픽스이기 때문에 이미지가 더 나은 품질이 될 수 있도록 PNG로 전환했습니다. 어쨌든 여기 내 코드가 있습니다. 그것은로 내려갑니다 oBitmap.Save(), 그런 다음 "GDI+에서 일반적인 오류가 발생했습니다"로 죽습니다.

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    context.Response.ContentType = "image/png"
    context.Response.Clear()
    context.Response.BufferOutput = True

    Try
        Dim oText As String = context.Server.HtmlDecode(context.Request.QueryString("t"))
        If String.IsNullOrEmpty(oText) Then oText = "Placeholder"
        Dim oPType As String = context.Server.HtmlDecode(context.Request.QueryString("p"))
        If String.IsNullOrEmpty(oPType) Then oPType = "none"

        Dim imgPath As String = ""
        Select Case oPType
            Case "c"
                imgPath = "img/banner_green.png"
            Case "m"
                imgPath = "img/banner_blue.png"
            Case Else
                Throw New Exception("no ptype")
        End Select

        Dim oBitmap As Bitmap = New Bitmap(context.Server.MapPath(imgPath))
        Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
        Dim frontColorBrush As New SolidBrush(Color.White)
        Dim oFont As New Font(FONT_NAME, 30)


        Dim oInfo() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders
        Dim oEncoderParams As New EncoderParameters(2)
        Dim xOffset As Single = Math.Round((oBitmap.Height - oFont.Height) / 2, MidpointRounding.ToEven)
        Dim oPoint As New PointF(275.0F, xOffset + 10)

        oEncoderParams.Param(0) = New EncoderParameter(Encoder.Quality, 100L)
        oEncoderParams.Param(1) = New EncoderParameter(Encoder.ColorDepth,8L)

        oGraphic.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
        oGraphic.DrawString(oText, oFont, frontColorBrush, oPoint)
        oBitmap.Save(context.Response.OutputStream, oInfo(4), oEncoderParams)
        context.Response.Output.Write(oBitmap)

        oFont.Dispose()
        oGraphic.Dispose()
        oBitmap.Dispose()  
        context.Response.Flush()
    Catch ex As Exception

    End Try
End Sub

JPEG 버전에서 내가 한 유일한 변경 사항은 다음과 같습니다.

  • context.Response.ContentType = "image/jpeg" 바뀌었다 "image/png"
  • 변경된 기본 이미지 (img/banner_green.jpg, img/banner_blue.jpg) 에게 .png
  • 색 깊이를 지정하는 두 번째 인코딩 매개 변수를 추가했습니다
  • 변경 oInfo(1) (JPEG)로 oInfo(4) (PNG)

PNG를 제대로 생성하기 위해이 루틴을 얻기 위해 조정해야 할 것이 더 있습니까?

도움이 되었습니까?

해결책

에 따르면 이 게시물, bitmap.save는 httpresponse.outputstream이 아닌 PNG로 저장하려면 원하는 스트림이 필요합니다. 이미지를 먼저 메모리 스트림에 저장 한 다음 IT의 내용을 응답으로 복사해야합니다.

Dim tempStream as New MemoryStream
oBitmap.Save(tempStream, ImageFormat.Png, oEncoderParams)
Response.OutputStream.Write(tempStream.ToArray(), 0, tempStream.Length)

또한 라인에 유의하십시오

context.Response.Output.Write(oBitmap)

아마도 당신이 기대하는 것과는 다른 일을합니다. HttpResponse.Output TextWriter이며 여기에서 사용하는 과부하입니다. TextWriter.Write(object) 객체에서 Tostring을 호출하고 결과를 스트림에 씁니다.이 경우 출력에 "System.Drawing.Bitmap"을 작성하는 결과.

다른 팁

응답을 플러시하기 전에 비트 맵을 처리하고 있습니까? 주위를 뒤집어보십시오. 또한 스트림에 비트 맵을 두 번 쓰는 것처럼 보입니다. 왜 그렇게하고 있는지 잘 모르겠습니다. 비트 맵을 출력 스트림에 저장하거나 응답 객체의 쓰기 메소드를 사용하지만 둘 다가 아닙니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top