1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Base64バイナリで受け取ったファイルをStreamで画像として保存する

Last updated at Posted at 2023-07-18

Base64バイナリで受け取ったファイルをStreamで画像として保存する

BASP21を使用してます.

先頭でページの文字コードをUTF-8にしておきます,

<%@ CodePage=65001 %> 

BASP21でバイナリを読み込む.

Set bobj = Server.CreateObject("basp21")
byteArray = Request.BinaryRead(Request.TotalBytes)
' 画像送信時にフォームのnameに「image」と名前を付けて送信しておく
sarray = bobj.FormBinary(byteArray,"image")

読み込んだバイナリをStreamでWindows-1252(utf-8のWin版かな?)文字列に変換し,変数「str」に保存.
「image,base64の画像本体」となっているのでカンマでSplitしてbaseに保存.
このとき,<%@ CodePage=65001 %> でASPファイルを明示的に文字コードをUTF-8の宣言しておかないと文字化けしてうまくいかなかったです.

dim stream : set stream = server.CreateObject("ADODB.stream")
stream.type = 1 'TypeBinary
stream.mode = 3 ' read write
stream.Open
stream.write(sarray)
stream.Position = 0
stream.Type = 2 ' TypeText
stream.Charset = "Windows-1252"
str = stream.ReadText ' binary to string
stream.close
set stream = nothing

base = Split(str,",") 

base(1)の本体部分をDOMDocumentのBase64Dataを使ってBase64デコードする.

' string Base64 decode
Set objXML = Server.CreateObject("MSXml2.DOMDocument")
Set objDocElem = objXML.createElement("Base64Data")
objDocElem.DataType = "bin.base64"
objDocElem.text = base(1) 'the base64-encoded string
imgdata = objDocElem.NodeTypedValue

imgdataに画像バイナリが格納されているのでStreanでpng画像としてサーバに保存します.

' 画像ファイルを保存
FileName = "D:\folder\picture.png"

set stream = server.CreateObject("ADODB.stream")
stream.type = 1 'TypeBinary
stream.mode = 3 ' read write
stream.Open
stream.write(imgdata)
stream.SaveToFile FileNa

今回はJPG・PNG問わずPNGで保存するような仕様にしました.送信時にJavaScriptでCanvasに一度描画して画像サイズを縮小しているため,バイナリに拡張子の情報自体がないのだと思います.
入力ファイルに拡張子が存在する場合,Streamでの画像保存時に元の拡張子を考慮する必要があるかもしれません.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?