Delphi มาแปลง Base64 ให้เป็นรูปภาพกันเถอะ (Base64 to image delphi)

ผมได้โจทย์มาว่า ดึงข้อมูลจาก JSON มาแล้วมีรูปภาพติดมาในรูปแบบ ตัวหนังสือยาวๆ (Base64) จะทำไงให้มันกลายเป็นรูปภาพ

อันดับแรกผมก็จะเช็คก่อนว่ามันเป็น Base64 จริงไหม โดยการ copy code ไปวางที่

https://codebeautify.org/base64-to-image-converter แล้วกด Generate Image

ถ้ารูปภาพขึ้นก็แสดงว่ามาถูกทางแล้ว ที่นี้มาดูที่ Code ก่อนอื่นเลยก็นำ Component

Memo image และ button มาวางในลักษณะนี้นะครับ

ในส่วนของ implementation ให้เพิ่ม uses

uses System.NetEncoding, jpeg, pngimage;

ในส่วนของปุ่ม convert ให้เพิ่ม code ดังนี้

procedure TForm5.BtnConvertClick(Sender: TObject);
var
LInput: TMemoryStream;
LOutput: TMemoryStream;
beginLInput := TMemoryStream.Create;
LOutput := TMemoryStream.Create;
tryMemo1.Lines.SaveToStream(LInput);
LInput.Position := 0;
TNetEncoding.Base64.Decode( LInput, LOutput );
LOutput.Position := 0;
//Image1.Picture.Bitmap.AlphaFormat := afIgnored;
Image1.Picture.LoadFromStream(LOutput);
finally
LInput.Free;
LOutput.Free;
end;
end;

เมื่อกด Run ก็จะได้หน้าตาประมาณนี้ ไม่แนะนำให้ copy base64 text มาวางใน memo ทิ้งไว้ก่อนกด run นะครับ มันจะ error

นำ base64 text ที่ได้มาไปวางใน memo แล้วกด convert

ก็จะได้ภาพดังนี้

ในกรณีที่เอาไปใช้จริงเราจะได้ base64 text มาจาก respond ของ api มาในรูปแบบ JSON ให้เรา base64 text ไปเป็น stream เลย โดยนำเอาตัวแปรประเภท TStringList มาใช้รับแทน memo

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response

More from Piyanat Nimkhuntod