基于C#的Botbuilder聊天机器人:嵌入Base64图片到ThumbnailCard
Embedding Base64 Images into a ThumbnailCard for C# Chatbot
Got it, let's get that base64 image from your database into the profile card. Here's the modified version of your CreateProfileCard method with full support for embedding the image:
internal static ThumbnailCard CreateProfileCard(Belegplan profile) { // Convert the base64 image to a valid data URI for the card CardImage profileImage = null; if (!string.IsNullOrWhiteSpace(profile.ProfileImageBase64)) { // Replace "image/png" with your actual image MIME type (e.g., image/jpeg for JPGs) string imageDataUri = $"data:image/png;base64,{profile.ProfileImageBase64}"; profileImage = new CardImage(imageDataUri); } ThumbnailCard card = new ThumbnailCard() { Title = $"{profile.Nachname}, {profile.Vorname}", Text = $"({profile.Bereich}-{profile.Jobtitel}). {profile.SitznummerGesamt}:: Stockwerk: {profile.Stockwerk}, Tischgruppe: {profile.Tischgruppe}, Sitznummer:{profile.Sitzplatz?.ToString()}.", // Add the image to the card's image collection (empty if no image exists) Images = profileImage != null ? new List<CardImage> { profileImage } : new List<CardImage>() }; return card; }
Key Things to Keep in Mind:
- Validate the base64 string: We check if
ProfileImageBase64(adjust this to match your actualBelegplanproperty name) isn't empty to avoid null reference errors. - Data URI Prefix: The
data:image/png;base64,part is mandatory—it tells the chat client how to parse the base64 data. If your images are JPGs, swapimage/pngforimage/jpeg. - Pre-prefixed base64: If your database already stores the base64 string with the full
data:image/...prefix, you can skip concatenating it and pass the stored string directly toCardImage. - Images Collection:
ThumbnailCard.Imagesexpects anIList<CardImage>, so we either add our image to a new list or return an empty list when there's no image available.
Optional Dynamic Format Handling:
If you need to support multiple image types, add an ImageMimeType property to your Belegplan class to store the correct MIME type for each profile. Then update the data URI line to:
string imageDataUri = $"data:{profile.ImageMimeType};base64,{profile.ProfileImageBase64}";
内容的提问来源于stack exchange,提问作者blfuentes
相关产品推荐
相关产品推荐

