How to load List<Asset> from url with Flutter multi_image_picker: ^4.7.14 - image

I am using Flutter multi_image_picker: ^4.7.14 to upload selected photos to server.
It stores images List, In my app new insert part is ok, I am getting the selected images and showing them in a gridview and sent them to the server.
But when I try to update my record, I don't understand how to get my record's images and set them to List. I have the url path of my uploaded images for that record. I want to get images and convert them to List because multi_image_picker is only accepting Asset, but there is no obvious explanation in multi_image_picker read me how to do this.
var images = List<Asset>;
for (var i = 0; i < tempList.length; i++) {
log("image link:" + ad_url + tempList[i].imageDownloadUrl);
final ByteData imageData = await NetworkAssetBundle(
Uri.parse(ad_url + tempList[i].imageDownloadUrl))
.load("");
final Uint8List bytes = imageData.buffer.asUint8List();
Image img = Image.memory(bytes);
// in this part I want to convert img to Asset , but I don't know how to do this.
Asset asset = img.... //How can I do this conversion
images.add(asset);
}

Related

Setting link URL with Google Docs API doesn't result in update of image

I'm trying to update a placeholder image with a new image that has an updated URL. The URL in fact is a valid Google Static Map URL that I'm using in other contexts successfully. I'm using the Google Document API to manipulate the document. Following the code I've been using:
var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
var imageMap = element.asInlineImage();
// if there was an image found in document
if (imageMap != null) {
// get current parent and index inside parent
var parent = imageMap.getParent();
var childIndex = parent.getChildIndex(imageMap);
// remove image from paragraph
imageMap = imageMap.removeFromParent();
// get static image url for territory
var url = getStaticMapURLForTerritory(id);
Logger.log(url);
imageMap.setLinkUrl(url);
// create a new image
parent.insertInlineImage(childIndex, imageMap)
}
This seems to work fine in that it does update the image url correctly. However, the image itself (the result of the url) is not updated. When I click on the link URL it does return the correct image.
Is there a way to force a refetch of the image blob associated with the URL? I've also attempted to use UrlFetchApp but that complains about a missing size parameter (google static api) which is certainly included in the url string and within the max 640x640 bounds.
I've exhausted all my options unless....
TIA, --Paul
setLinkUrl only does that: sets the link. To actually add a new image you'll have to get its blob:
function replaceImage() {
// [...]
// get static image url for territory
const url = getStaticMapURLForTerritory(id)
const response = UrlFetchApp.fetch(url)
// create a new image
parent.insertInlineImage(childIndex, response.getBlob())
.setAltDescription(img.getAltDescription())
.setAltTitle(img.getAltTitle())
.setWidth(img.getWidth())
.setHeight(img.getHeight())
.setLinkUrl(url)
}
References
Class InlineImage (Google Apps Script reference)

Insert Image into a Google Sheet with Apps Script using base64 encoded data

Given some base64 encoded data for a png file, as in the example below from the image tag.
<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
I need to create an image blob from the base64 encoded data for the insertImage() method.
sheetClass.insertImage(imageBlob, column, row)
Documentation:
Sheets Class - insertImage method
I've tried using the code below, but it throws the error:
Execution failed: Error retrieving image from URL or bad URL
The documentation states that the method needs a blob, not a URL, but it seems like it's expecting a link to an image file.
function insertImageFromBase64Src() {
var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';
var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png').getBytes();
var ss = SpreadsheetApp.getActiveSpreadsheet();//This code is bound to a Sheet
var po = {
shName:'Update File',
column:1,
row:37
}
var sh = ss.getSheetByName(po.shName);
var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}
How about this modification?
Modification points:
insertImage can use the blob and URL which is the direct link of the image file.
In your script, imageBlob is an byte array which is "number[]". By this, I think that an error occurs.
Please add the name to the blob.
When the name is not given, an error occurs.
Modified script:
When your script is modified, it becomes as follows.
function insertImageFromBase64Src2() {
var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';
var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png', 'sample'); // Modified
var ss = SpreadsheetApp.getActiveSpreadsheet(); //This code is bound to a Sheet
var po = {
shName:'Update File',
column:1,
row:37
}
var sh = ss.getSheetByName(po.shName);
var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}
In this modification, it supposes that data can be correctly decoded.
References:
insertImage(blobSource, column, row)
insertImage(url, column, row)
If this was not the direct solution of your issue, I apologize.

Send an image rather than a link

I'm using the Microsoft Bot Framework with Cognitive Services to generate images from a source image that the user uploads via the bot. I'm using C#.
The Cognitive Services API returns a byte[] or a Stream representing the treated image.
How can I send that image directly to my user? All the docs and samples seem to point to me having to host the image as a publically addressable URL and send a link. I can do this but I'd rather not.
Does anyone know how to simple return the image, kind of like the Caption Bot does?
You should be able to use something like this:
var message = activity.CreateReply("");
message.Type = "message";
message.Attachments = new List<Attachment>();
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("https://placeholdit.imgix.net/~text?txtsize=35&txt=image-data&w=120&h=120");
string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
message.Attachments.Add(new Attachment { ContentUrl = url, ContentType = "image/png" });
await _client.Conversations.ReplyToActivityAsync(message);
The image source of HTML image elements can be a data URI that contains the image directly rather than a URL for downloading the image. The following overloaded functions will take any valid image and encode it as a JPEG data URI string that may be provided directly to the src property of HTML elements to display the image. If you know ahead of time the format of the image returned, then you might be able to save some processing by not re-encoding the image as JPEG by just returning the image encoded as base 64 with the appropriate image data URI prefix.
public string ImageToBase64(System.IO.Stream stream)
{
// Create bitmap from stream
using (System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromStream(stream) as System.Drawing.Bitmap)
{
// Save to memory stream as jpeg to set known format. Could also use PNG with changes to bitmap save
// and returned data prefix below
byte[] outputBytes = null;
using (System.IO.MemoryStream outputStream = new System.IO.MemoryStream())
{
bitmap.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
outputBytes = outputStream.ToArray();
}
// Encoded image byte array and prepend proper prefix for image data. Result can be used as HTML image source directly
string output = string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(outputBytes));
return output;
}
}
public string ImageToBase64(byte[] bytes)
{
using (System.IO.MemoryStream inputStream = new System.IO.MemoryStream())
{
inputStream.Write(bytes, 0, bytes.Length);
return ImageToBase64(inputStream);
}
}

How do i display images in Microsoft bot framework with only the base64 encoded string of the image?

i tried the below code, and here is the output i get in emulator
message.Attachments.Add(new Attachment()
{
ContentUrl = $"data:image/jpeg;base64,xxxx"
});
There appears to be a max size for data uri images, however your initial code looks good to me and isn't throwing an explicit internal server error (as it would if the datauri is too large).
I've implemented something similar:
var reply = message.CreateReply("Here's a **datauri image attachment**");
reply.Attachments = new List<Attachment> {
new Attachment()
{
ContentUrl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAQABADAREAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAACAUH/8QAJhAAAQMDAwQCAwAAAAAAAAAAAQIDBQQGEQcIEgATISIUMRUjUf/EABYBAQEBAAAAAAAAAAAAAAAAAAMBBP/EAB8RAAICAQQDAAAAAAAAAAAAAAECAAMRBBITIiFB8P/aAAwDAQACEQMRAD8AubjdVbtj5cQFi3tX2lS/ka16Rko9pZqHHfklplgKAylJPNR/vEZPWyvTpUN7jMyK3M21fE03ZLuQ1Gmbyc0j1Dudq7o8RztXFzXEGtacZeQhxipKT7D9qcKUOQ+skfRWKrdqxj71HI4erHME97633Fc+pF10c64pIg7ll6CldoEcHEoTVL7fMZ9se2CPOekdkCiSjIYmLvYvMRdLQPXDG3FGSEzK1iKB4rYCnaan7oVwcCQCHVqGTkkeEefGOgbTtjccyW6sM4QAT//Z",
ContentType = "image/jpg",
Name = "datauri"
}
};
Which results in the emulator showing this image (I need more rep to embed images.. ugh..)
Update: a data uri version of a ~20kb image works just fine, however a data uri version of a ~140kb image fails with a "500 internalservererror" in the emulator. Guess there is a size limit after all..
As such, can you validate that he datauri you're using is a valid image? Can you create a simple html page with an img element, paste in the value in your ContentUrl and see the image in the html page? Or even just paste it into a browser address bar.
When you want to display images you can use markdowns.
var replyMessage = "[ImgName](" + ImagesUrl + ")";
return message.CreateReplyMessage(replyMessage);
Bot Framework Markdown Documentation
================= Convert Base64 string to Image ==========================
public void SaveImage(string base64)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save("SavingPath" + "ImageName.jpg");
}
}
}
Then you can use the URL.

Windows phone 8 retrieving image from web service?

I'm trying to set the source attribute of an Image element to an image in my localhost, basically what I'm doing is display a list with items, their description, price and an image. I get all these values from a web service which returns the url where the image is in the local server Eg: http://localhost/roses.png, when the list of items is displayed all values are set correctly but the Image element does not show the image.
Web service returns the data in JSON format. Eg:
[{"ImagenUrl":"http://localhost/roses3.png", .... ]
code on client_actionCompleted method:
if (e.Result != null)
{
dynamic jsonObj = JsonConvert.DeserializeObject(e.Result);
foreach(var v in jsonObj)
{
Debug.WriteLine("IMAGE URL ==> " + (string)v.ImagenUrl);
FlowersItems fi = new FlowersItems();
fi.fi_name.Text = (string)v.Nombre;
fi.fi_price.Text = (string) v.Precio;
BitmapImage tn = new BitmapImage(new Uri((string)v.ImagenUrl, UriKind.Absolute));
fi.fi_image.Source = tn;
FlowersItemsListbox.Items.Add(fi);
}
}
As I said before the fi_name and fi_price text is set correctly but the fi_image is not displayed even though I can view the image in my browser going to the url returned by the web service just fine.
Any ideas on how to make this work?
Edit: just in case, I also tried new Uri((string)v.ImagenUrl)
without the UriKind.Absolute parameter.

Resources