Tuesday, July 4, 2017

Loading Lots Of Images From Server In Android

Leave a Comment

I searched about it on Google and also found various good results. But since I'm not expert in server and backend kind of terms, I would like to ask it in a separate question. I have a website hosting which helps me run an institution's website.

  1. In my android app, there should be an option such as "Photo Gallery" which shows images from my website (where I upload images in a folder). I think it can be done by managing some JSON files.

  2. Let there be a folder \public_html\MyApp\Images which consists of folders like "Event1", "Event2", and so on. I upload images to these different folders and my Android app should load them (maybe separately giving users a choice to pick a folder).

Is it possible? If any advanced database system is required, please give me some intro links for that. Is there any way a JSON is automatically generated containing the links to images?

Edit: I had recently bought website hosting for backend kind of things and I haven't done any server-side scripting or anything. That's why a detailed answer is required. I don't know how to manage those images, simply upload images and put links in JSON or use some MySQL, SQL or whatever terms which I've never used.

9 Answers

Answers 1

By the looks of it, you need 2 new database tables. One to store your albums, the other to store the individual images.

CREATE TABLE `album` (    `album_id` INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,    `album_name` VARCHAR(255) NOT NULL,    `album_date` DATE NOT NULL); 

album would store all the album metadata so it would store Event1 with its details, Event2 and so on..

CREATE TABLE `images` (    `image_id` INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,    `album_id` INT(11) NOT NULL,    `image_date` DATE NOT NULL,    `image_path` VARCHAR(255) NOT NULL, FOREIGN KEY (album_id) REFERENCES album(album_id)); 

images would store all the images with their paths and the albums which they belong to using the album_id as the foreign key

Your queries for all images would be

SELECT * FROM `images`; 

Images from a particular album would be queried like

SELECT * FROM `images` WHERE `album_id` = *YOUR_ID*; 

The output from the SQL query can be JSON encoded using

json_encode($query_result); //PHP code 

EDIT: Gallery App Example On Android Hive

It seems like you're saving images as BLOB directly into the database hence it's giving you the 64kb limit. It is better if you save paths of the images. If that is not possible then base64 encode the images and store them in a column of type VARCHAR.

Answers 2

Sorry for my english, You can add folder name in database when creating folder and load all folder name in app and also save images name in database with folder name table primery key as foreign key and when user select folder name use that folder name primery key and get all images with that key and load it in app.

Answers 3

Sorry for bad english...

This images are saved as Blob type on your database or you save some kind of link to it?

You can send some kind of HTTP request with the folder name and then build a json with the images data. I use the Volley lib for HTTP requests in my app, very easy and work well

Answers 4

Yes you can really do this, it's possible and also practical, since you have a server. The first thing to do is to make an API with this api you can make URLs that android can fetch the JSON data from as objects, this means also you have to convert the images path to JSON. This great tutorial explains all about the process and even more. Since you're loading large number I suggest you use Picasso for the image caching and also recycler view

https://www.simplifiedcoding.net/android-programming-tutorial-to-get-all-images-from-server/

Happy coding!

Answers 5

You may get path of all images from server in JSON and display images by passing path with the help of Picasso library as -

Picasso.with(context).load("imagepath").into(imageView); 

Answers 6

You try to encode all the images in base64 then insert into database then create api which fetch all the images from your database then you sync your android app with this api and store the images as sqlite in local database. 1.main profit is that now u can load your gallery imges offline also

Answers 7

The blob type can be different. On one side he can mean the sql blob type. And most important is the MIME Type like here

If you are coding your API / Backend in Java it can look like this to stream an image to the client which requested the blob:

public javax.ws.rs.core.Response exportBlob( String blobName ) throws Exception {   Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex); //query the blob from the Database   String type = "image/png"; // Set your needed MIME Type   StreamingOutput data = createStreamingOutput( imageBlob ); // stream it as a binary   return Response.ok( data, type ).build(); }   /**    * Creates an Outputstream of the Data from the given Blob.    *    * @param blob the blob that needs to be converted.    * @return Outputstream of the Blob Data.    * @throws WebApplicationException when the conversion failed.    */   private static StreamingOutput createStreamingOutput( final java.sql.Blob blob )   {     return output -> {       try ( InputStream stream = blob.getBinaryStream() )       {             byte[] buff = new byte[4096];             int count;             while ( ( count = stream.read( buff ) ) != -1 )             {                if ( count > 0 )               {                 output.write( buff, 0, count );               }            }       }       catch ( SQLException e )       {         throw new WebApplicationException( e.getMessage(), e );       }     };   } 

Converting it to Base64 is also an option. You have to adapt to what you can use in android to convert this binaryData back to an image again.

An example for android could be this:

//byteArray is what you recieved from the API in this example Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length); 

EDIT:

Since you stated that you have very few knowledge in this type of scenario let me add some resources.

  1. How to save an actual image in a MySQL database here (This is not that different for other databases, besides syntax)
  2. A little confusing example of BLOB handling at php here
  3. A example for handling BLOBs in Java here

There are often discussions about using BLOBs to save images. You could make life really really easy with just adding the base64 representation of an image in the database. This way you wouldn't need to handle the dataType BLOB. However I generally don't like that solution personally and prefer using BLOBs. ( I already added a article about blob so I won't do it again)

Also here are some links for getting into Backend development, but that's the part where your own effort comes into place. It's a lot to learn but don't be scared. Once you completed your base it will become simpler.

Java Frameworks

Interesting PHP Frameworks

PHP Backend Tutorial

Online course

Good luck on your journey!

Answers 8

This solution does not need database.

You need two API endpoints in PHP

Upload images /api/upload

<?php  $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) {     $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);     if($check !== false) {         echo "File is an image - " . $check["mime"] . ".";         $uploadOk = 1;     } else {         echo "File is not an image.";         $uploadOk = 0;     } } // Check if file already exists if (file_exists($target_file)) {     echo "Sorry, file already exists.";     $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) {     echo "Sorry, your file is too large.";     $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {     echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";     $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) {     echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else {     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {         echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";     } else {         echo "Sorry, there was an error uploading your file.";     } } ?> 
  1. List images

First list all directories under the upload directory:

$array = glob("uploads/*", GLOB_ONLYDIR); echo json_encode($array); 
  1. If you want a specific folder, you can do so by sending the folder name and append to request URL and list all files.

    $array = glob("uploads/".$_REQUEST['dir']."/*"); echo json_encode($array);

EDIT

// provides the current working directory echo getcwd() ."\r\n"; // then navigate to path // glob(getcwd() . DIRECTORY_OF_IMAGES)); // GLOB_BRACE tells to find all extensions in the brace $array = glob(getcwd() . "/web/bundles/img/*.{jpg,gif,png}", GLOB_BRACE); 

Read this article http://php.net/manual/en/function.glob.php

Answers 9

See, If you have your hosting account on hostinger, you'd get an option to create your own database without even writing a single line of mysql code. For server side, you need to learn Php. Also, it is never recommended to store images in the database. Store them in your storage directory on your hosting site, and their links(URL) in the database. It would make fetching of Images faster.

For the android side, just use Picasso library which saves you time and space to load images from server.

You are all set to go. :) Comment for queries.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment