Loading image from storage - codenameone

I have an image that I loaded by using URLImage class. Here is the code:
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(getWidth()/2, getWidth()/2 , 0xF92D2D), true);
Image originImg = URLImage.createToStorage(placeholder, imgFileName, photo_url);
To my understanding, this image is being saved into Storage with createToStorage() method. However, next time when I am loading this form, I don't want to download the image again, I want to take it from the Storage, because its faster.
So what I did, I added check :
if (Storage.getInstance().exists(imgFileName)) {
// Take the image from the Storage
originImg = Image.createImage(Storage.getInstance().createInputStream(imgFileName));
} else {
// Load the image with URLImage class.
}
However, it seems like my file is never saved into the Storage. What can be wrong?

You don't need to do that. URLImage seamlessly loads the file from storage if the file is already there. You can open the network monitor and see if a request is made to the URL for this specific image.
I'm not sure why the Storage.getInstance().exists(imgFileName) method would fail. I assume the image name is different in the different execution or something of that sort. You can see that images are created in your .cn1 directory.

Related

Show new image after upload

Quick question, using the Baqend SDK in React, I'm saving profile images using the id of an object saved in the database as the name.
But in order to get the image to update in the user's browser after it is uploaded, I'm modifying state and adding &updated=true to the end of the file.url as it is returned by Baqend.
The save image code:
uploadLogo(event) {
event.preventDefault();
const name = this.props.match.params.id+"logo";
const file = event.target.files[0];
const img = new db.File({ name: name, data: file, type: 'blob' });
img.upload({force: true}).then((file) => {
db.Companies.load(this.props.match.params.id).then(company => {
this.setState({
logo: file.url+"?updated=true"
});
company.logo = file.url;
return company.update();
},
(error) => {
alert(error);
});
});
}
Is this the correct approach with React and the Baqend SDK? Are there going to be any side-effects on this if I'm loading a bunch of images by URL that look like this: https://remarkable-apple-95.app.baqend.com/v1/file/www/cce9830b-48eb-422e-830d-72ae28571480logo?BCB&updated=true
I would imagine url parameters like this are just ignored? The only person that is going to load the image with ?updated=true after it is the one person that updates the logo and only immediately after he updates it.
Also what is the ?BCB being added in file.url doing?
Your example looks good so far.
But you should not add additional query parameters at all, as they cause cache misses in the CDN.
The BCB (Baqend Cache Buster) is actually what you are trying to archive with the ?upload=true parameter. The SDK adds those cache busters automatically if an image was changed previously.
The BCB ensures that the fresh image is fetched from the server and is only cached with revalidation headers until the old image is expired in the browser cache. Our CDN caches are aware of this special cache buster and rewrite the image request back to the original URL to ensure cache hits in the CDN.
Note that our CDN caches are instantly invalidated if the content is changed.
This staleness information is propagated to other clients as well via a Bloom filter. That ensures that other clients won't take the image out of their local cache and therefore see the new image too.

Error Image Upload and Get, Method App\Image::__toString() must not throw an exception, caught Illuminate\Database\Eloquent\JsonEncodingException

I am uploading user profile image which is uploading and moved to storage/app/upload/images folder but when I am trying to display that image, below given error occurs.
Method App\Image::__toString() must not throw an exception, caught Illuminate\Database\Eloquent\JsonEncodingException
Here is my controller function for displaying
public function userProfile() {
$image = Image::all();
return view('frontend.layouts.Profile',compact('image'));
}
My view in which I am displaying image
#foreach($image as $images)
<img style="width:210px ; height: 230px " src="/storage/app/upload/images/{{$images->image}}" >
#endforeach
Please Upload your image in Public directory and then try to access that, it will work fine
There are three ways of making an image available to a user:
1. As a public asset
Here the image is made available to everyone. For instance your website logo, or landing page image would be accessed by all. So there is a url to the image that is easily accessed by all. These sort of files would go straight to public/img/ folder.
2. As a protected image available only if specific url is requested
Here user specific images would be accessed by specific people. Think of your members' personal photos that you want to make available only to the member herself or to some specific person. In this case you would store the images in storage/app/public and make a symlink using the artisan command php artisan storage:link You can read more on this here. Assuming that you store your files using random names using str_random() you would then generate urls to your image using the asset() helper like: echo asset('storage/X3jf5j5b2j3n.jpg'); Given that the file names are random, it would be hard to access this image by everyone excepting those who have the url generated using the asset() helper.
3. As a protected image made available using Intervention library
In this case you would first check if user is logged in and then dynamically load the image using Intervention via another protected route. So in your web routes you would first have the user authorization using auth middleware:
Route::group(['middleware' => 'auth'], function () {
Route::get('user', 'UserController#userProfile');
Route::get('images/{image}', 'UserController#serveImage'); // this route serves the image only if user is logged in
});
Then once your have installed Intervention library using composer, our UserController would look like:
use Intervention;
class UserController extends Controller
{
public function userProfile()
{
$images = Image::all();
return view('frontend.layouts.Profile', compact('images'));
}
public function serveImage($image)
{
$filename = storage_path('app/images/'.$image);
return Intervention::make($filename)->response();
}
}
You can see that the image is now being served from the storage folder and not public folder. So this method serveImage() is called only when the route defined earlier for it is authorized. Intervention then works its magic to read the image and send it as a http response.
Your view would change one tad bit to accommodate the new route end point that we defined called images. I assume here that you are storing the filename of the image in db by a field named filename:
#foreach($images as $image)
<img style="width:210px ; height: 230px " src="{{ url('/images/'.$image->filename) }}" >
#endforeach
Note: Do bear in mind that the preferred way to serve images is by using method 2 since it is much faster. You can use method 3 sparingly if you really don't want anyone to even stumble upon the files using the urls.

Opened file gets cached in titanium. Cant view replaced file content while app is running

I am facing a slight issue while editing a file.
I am saving a file (image) with a certain name on ios using the code below.
But the problem is that when i replace the image stored in a file (eg temp.jpg) the app still picks up the previous image when i open the file. However the new image can be seen in the explorer.
If i restart the app the new image appears while opening the image.
var folder = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'DocImages');
// DocImages is a folder for files
// ImageVar contains the blob for the new image from camera or gallery
// docImgModel is the model class containing the name and image path of the image
if(imageVar !== null && imageVar !== undefined){
if (docImgModel.imagePath !== null && docImgModel.imagePath !== undefined){
tempFile = Ti.Filesystem.getFile(docImgModel.imagePath);
if (tempFile.exists()) {
tempFile.deleteFile(); // deleting already existing file
}}
// in case of changing the image stored in a file(the case in which i have a
// problem) the imgFile(below) is same as docImgModel.imagePath (above)
imgFile = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory + 'DocImages/', filenameWithExtension); // creating a new file
// writing image to file
imgFile.write(imageVar);
Ti.API.info('new image saved');
}
}
I was wondering if titanium saves cache of the file already opened and is hence not able to show the new image.
If not, is there anything else i am doing wrong or something i could do to make it work.
I just want to show the new saved image. Is there any way to do it.
Thanks.
I haven't worked with opening files from the device, but I ran into a similar issue when trying to update data on my screen. If you are saying when you open the app and it loads the correct image comes up, then the code that you use to load the image appears correct and working. I assume that is the code you posted above. Even that appears to be a code fragment of a more complete file.
You didn't post any UI code, which is probably where your real problem is coming from. You have an object, a view of some sort I'm guessing, that is already rendered using the old image before you load the new image. So debugging, you might see the new image's data loaded in the code above, but the UI element hasn't been assigned or updated correctly.
As a test, I would suggest that you put some test code into your app that allows you to destroy your UI elements and recreate them, you will probably see the picture come up properly in that case.
According to this post: http://developer.appcelerator.com/question/31181/simple-image-refresh
Just assigning the image you loaded to the url of the image should update it. Your example code doesn't show the image object that you are attempting to update and how that communication is made from the code that is loading the image.
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
var image1 = 'image1.png';
var image2 = 'image2.png';
//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
title:'Tab 1',
backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Tab 1',
window:win1
});
var img = Titanium.UI.createImageView({
width:100,
height:100,
top:50,
left:110,
url:image1
});
win1.add(img);
var btn = Titanium.UI.createButton({
title:'load',
width:100,
height:35,
top:50,
left:0
});
function switchImage(){
if(img.url == image1){
img.url = image2;
} else {
img.url = image1;
}
}
btn.addEventListener('click',function(){
switchImage();
});
setInterval(switchImage,3000);
win1.add(btn);
//
// add tabs
//
tabGroup.addTab(tab1);
// open tab group
tabGroup.open();

make a copy of an image in blobstore

I have an image in blob store which is uploaded by users(their profile pic). I want to make a copy of the same and and re-size the copy so that it can be displayed as a thumbnail. I want to make a copy of the same instead of using the ImageService because this would be used more often compared to the profile image.
What I am doing here is this:
reader = profile_image.open() #get binary data from blob
data = reader.read()
file_name = files.blobstore.create(mime_type=profile_image.content_type)#file to write to
with files.open(file_name, 'a') as f:
f.write(data)
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)
image = images.Image(blob_key = blob_key)
image.resize(width=32, height=32)
entity.small_profile_pic = <MyImageModel>(caption=<caption given by user>,
picture=str(blob_key))
This is giving me error:
BadValueError: Image instance must have a complete key before it can be stored as a reference.
I think this is because the blob is not saved(put()) into the datastore, but how do i do it. Doed files.blobstore.get_blob_key(file_name) not do it ?
I would also like to ask: does the blobstore also cache the dynamically transformed images images served using get_serving_url() ...
I would use the get_serving_url method. In the doc is stated that:
The get_serving_url() method allows you to generate a stable, dedicated URL for serving web-suitable image thumbnails. You simply store a single copy of your original image in Blobstore, and then request a high-performance per-image URL. This special URL can serve that image resized and/or cropped automatically, and serving from this URL does not incur any CPU or dynamic serving load on your application (though bandwidth is still charged as usual). Images are served with low latency from a highly optimized, cookieless infrastructure.
Also the code you posted doesn't seem to follow the exampled posted in the docs. I would use something like this
img = images.Image(blob_key=original_image_key)
img.resize(width=32, height=32)
thumbnail = img.execute_transforms(output_encoding=images.JPEG)
file_name = files.blobstore.create(mime_type='image/jpeg')#file to write to
with files.open(file_name, 'a') as f:
f.write(thumbnail)
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)

NSURL to File Path Monotouch

I am new to iphone development. I am writing my app in Mono touch.
I am trying to get a photo from the asset library which I can do successfully however I get the path as a URL "assets-library://asset/asset.JPG". I want to do a FileStream read which asks for a filepath. How can I convert NSURL to a file path?
I used asset.DefaultRepresentation.Url.AbsoluteString which gives the following filePath:
assets-library://asset/asset.JPG?id=1000000001&ext=JPG
then when it hits the FileStream(filePath, FileMode.Open, FileAccess.Read) it gives an exception stating that Could not find part of the path.
Please Help:)
The url you get from the assets library is not a file path. It is a url to a resource in the assets library, so you cannot use FileStream to read its data.
If the asset is an image, you can get its contents to an NSData object like this:
UIImage image = UIImage.FromImage(asset.DefaultRepresentation.GetImage());
NSData data = image.AsJPEG();
You can use two different static methods to load an image. FromImage and FromBundle. The first is asynchronous. The latter is synchronous (when an image is loaded the it is cashed by iOS). Both take the path to your image.
When you use these methods, property image must be set to content property. Right click on image, property -> set build action to content.

Resources