Display an image from URL - image

I need get an image from a URL and display in a view. How can do this in Cincom Smalltalk?
For example, I have this image URL:
http://news.bbcimg.co.uk/media/images/64001000/jpg/_64001280_63976026.jpg
And I wish display the image. I try:
|req content reader|
req := HttpRequest
get:'http://news.bbcimg.co.uk/media/images/64001000/jpg/_64001280_63976026.jpg' asURI.
content:=req execute.
reader := JPEGImageReader new.
reader from: content byteSource.
But it doesn't work. Cincom Smalltalk says:
Image incomplete or partially corrupted JFIF marker expected.
when I execute: JPEGImageReader>>parseFirstMarker.

The "byteSource" method is returning a stream that's already positioned to the end of file. When the JPEG reader starts to read, I hits the end and aborts.
You really shouldn't be using the byteSource method. If the contents of the URI are compressed, you won't get them properly decompressed. You should fetch the byteContents and open a readStream on that result as follows:
|req content reader image |
req := HttpRequest
get:'http://news.bbcimg.co.uk/media/images/64001000/jpg/_64001280_63976026.jpg' asURI.
content:=req execute.
reader := JPEGImageReader new.
image := (reader from: content byteContents readStream) image

Related

Not able to add image in header as well as in body part of word file using apache poi

I'm adding a picture in the header of a word document. It shows a frame for the image and says "the image cannot currently be displayed". If I add text to the header, it shows the text, and if I add the image in the document body, it also shows the image. So it is getting the image and it shows text on the header, but not the image.
XWPFHeader head = document.createHeader(HeaderFooterType.DEFAULT);
paragraph = head.getParagraphArray(0);
if (paragraph == null)
//paragraph = head.createParagraph();
paragraph=document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/Picture.png");
String imgFile = "static/Picture.png";
run = paragraph.createRun();
XWPFPicture picture= run.addPicture(inputStream, XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(100),
Units.toEMU(50));
System.out.println(picture); //XWPFPicture is added
System.out.println(picture.getPictureData()); //but without access to XWPFPictureData (no blipID)

How do I read/write image file with its original extension when you receive the image as bytes in Flutter?

Here is the problem I have:
My users can set their profile image either from Facebook (which is a jpeg or gif) or from local device (which could be png or jpg or others).
I get the image from Facebook by using:
// Get the name, email and picture
final graphResponse = await http.get(
'https://graph.facebook.com/v4.0/me?fields=name,email,picture.width(300).height(300)&access_token=$token');
// Decode JSON
final profile = jsonDecode(graphResponse.body);
final String stringData = profile['picture']['data'];
final bytes = Uint8List.fromList(stringData.codeUnits);
And getting image from local device by:
final imagePicker = ImagePicker();
// Call image picker
final pickedFile = await imagePicker.getImage(
source: ImageSource.gallery,
maxWidth: MAX_WIDTH_PROFILE_IMAGE,
);
final imageBytes = await pickedFile.readAsBytes();
Then all I got here are in bytes (Uint8List), how do I save it according to its original extension?
Then later on how do I read them again without checking its extension?
Such as with:
// Setting the filename
// Could be jpg or png or bmp or gif.
// How to determine the extension?
final filename = 'myProfileImage';
// Getting App's local directory
final Directory localRootDirectory =
await getApplicationDocumentsDirectory();
final String filePath = p.join(localRootDirectory.path, path, filename);
final file = File(filePath);
You see, when reading the file we need to specify the full filename. But how to determine the extension then ?
You can avoid dealing with extensions completely by simply not setting an extension in the filename. Extensions only exist to indicate what is likely contained within a file for an OS, but they are not necessary and aren't needed in your case especially since you know that you have some kind of image data in that file and you application is probably the only thing ever using that file.
However, if you really do want to use extensions in the filename, you can use the image package. This provides a Decoder abstract class with multiple implementers for a variety of image encoding methods. To determine which method was used for your file you could check with the isValidFile of each possible decoder type that you need and write an extension accordingly.
Example:
PngDecoder png = PngDecoder();
if(png.isValidFile(data //Uint8List inputted here)) {
print("This file is a PNG");
}

Error Converting Apps Script Blob from PNG to JPEG

I'm trying to download a PNG image in Apps Script, convert it to JPEG, and generate a data URI for this new JPEG.
function test() {
var blob = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob();
var jpeg = blob.getAs("image/jpeg");
var uri = 'data:image/jpeg;base64,' + Utilities.base64Encode(jpeg.getBytes());
Logger.log(uri);
}
When I run this, I get:
The image you are trying to use is invalid or corrupt.
Even something like:
function test() {
var bytes = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob().getBytes();
var jpeg = Utilities.newBlob(bytes, MimeType.PNG).getAs(MimeType.JPEG);
DriveApp.createFile(jpeg);
}
doesn't work.
Your code is correct. This may be a bug, but it's specific to the file you are using, so may as well be a bug in the file (i.e., the file could indeed be corrupted somehow). Or maybe it uses some features of PNG format that Google doesn't handle. Replacing the URL by another one, e.g.,
var blob = UrlFetchApp.fetch('https://cdn.sstatic.net/Sites/mathematica/img/logo#2.png').getBlob();
both functions work as expected.

Go base64 image decode

Im currently getting a base64 image data url from a canvas something like this (not the dataurl im getting just to show how the string looks like)
data:image/png;base64,iVkhdfjdAjdfirtn=
I need to decode that image to check the width and the height of the image
dataurl := strings.Replace(req.PostFormValue("dataurl"), "data:image/png;base64,", "", 1)
reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(dataurl))
c, _, err := image.DecodeConfig(reader)
if err != nil {
log.Fatal(err)
}
log.Println(c.Width)
But Im getting an error while trying to decode the config
Unknown image format
So yeah the way Im making the dataurl must be wrong but cant figure what to do. I also tried passing the full dataurl (with data:image...) still no success
What you have is a Data URI scheme, info on how to decode it and more on this is in this question and answer:
Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)
But note that image.Decodeconfig() will only decode image formats that are registered prior to calling this function, so you need the image format handlers to be registered in advance. This can be done with imports like
import _ "image/png"
More on this is in the package doc of image. Or if you know the exact format (e.g. in your example it's PNG), you can directly use png.DecodeConfig().
So it doesn't work for you because your actual encoded image is of PNG format, but you didn't register the the PNG format handler and so image.DecodeConfig() won't use the PNG handler (and so it will not be able to decode it => "Unknown image format").
Also note that replacing the prefix that is not part of the Base64 encoded image is a poor solution to get rid of it. Instead simply slice the input string:
input := "data:image/png;base64,iVkhdfjdAjdfirtn="
b64data := input[strings.IndexByte(input, ',')+1:]
Slicing a string will not even copy the string in memory, it will just create a new (two-word) string header.

Swift coding generate random number and link to image and sound

I am very new to both programming and swift (please be kind!). I have a working example of how to generate a random image (by assigning a number and using Int(arc4random_uniform(x)). However I do not know how I can say if this image is shown, then assign this sound to the button. Every time an image is displayed it will have a matching sound to go with it. With my limited experience I can only think of doing long winded if statements?
Answer
Pass the name of the image to a NSMutableString, without the extension (.png, or just remove the extension.). Then (hopefully the audio file has the same name as the images name) you can now call the audio file with from the mutableString.
Explanation
For Example. If you have an image named Dog.png. Name your audio file that goes with the dog image: dog.mp3. (.mp3 is an example). When the user selects the dog image, pass the name to a muatableString. Lets call the mutableString name selectedImage.
Right now, selectedImage should have a value of .png. (Or whatever extension you have.) Remove the last 3 letters of selectedImage like this:
func deleteCharactersInRange(_ aRange: NSRange)
Next you want to call the audio file using selectedImage, and add the extension name like this:
func appendString(_ aString: String)
So selectedImage's value should now be: dog.mp3. And you can now call the audio file with selectedImgae.
Hope this helps!!
Edit
Here is code to play audio files:
var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()

Resources