How to make YouTube video thumbnails in android? [duplicate] - android

This question already has answers here:
How to display thumbnail of YouTube Videos in Android
(8 answers)
Closed 6 years ago.
In my android Activity I want to play video from YouTube through YouTube application or some other. For that I want to load thumbnails of the video in my activity.
Is this possible? If so, how?

YouTube puts the thumbnails of the video at a specific predictable URL. It would be a bit of a pain, but I'm sure you could find a way to display the images from the URL, or to download them and then display them.
Here's information on my blog on what those thumbnail URLs are.
I'll copy and paste what I wrote in the blog post:
Look at the link for the video–for example, http://www.youtube.com/watch?v=GDFUdMvacI0
Take the video ID… the portion after “v=”, in this case GDFUdMvacI0. If the URL is longer than that, only go until the next ampersand. For example, http://www.youtube.com/watch?v=GDFUdMvacI0&feature=youtu.be is the same, GDFUdMvacI0.
Then just substitute your video ID for the video ID in the following URLs to these thumbnail images:
http://img.youtube.com/vi/GDFUdMvacI0/0.jpg
http://img.youtube.com/vi/GDFUdMvacI0/1.jpg
http://img.youtube.com/vi/GDFUdMvacI0/2.jpg
http://img.youtube.com/vi/GDFUdMvacI0/3.jpg
0.jpg is a full-sized image. The other three are very small (120×90) and are taken automatically by YouTube from three certain points in the video.

Download picasso jar file and put that jar file in "libs" folder
Use picasso to download image
Use method extractYoutubeId(url) to extract youtube id from YoutubeVideo Url
To get image of youtube video use given link and put youtube id in that url as below: "http://img.youtube.com/vi/"+extractYoutubeId(url)+"/0.jpg"
Youtube_Video_thumnail
package com.app.download_video_demo;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
// get Picasso jar file and put that jar file in libs folder
public class Youtube_Video_thumnail extends Activity
{
ImageView iv_youtube_thumnail,iv_play;
String videoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.youtube_video_activity);
init();
try
{
videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");
Log.e("VideoId is->","" + videoId);
String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video
// picasso jar file download image for u and set image in imagview
Picasso.with(Youtube_Video_thumnail.this)
.load(img_url)
.placeholder(R.drawable.ic_launcher)
.into(iv_youtube_thumnail);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
public void init()
{
iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
iv_play=(ImageView)findViewById(R.id.iv_play_pause);
}
// extract youtube video id and return that id
// ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
// videoid is-->t7UxjpUaL3Y
public String extractYoutubeId(String url) throws MalformedURLException {
String query = new URL(url).getQuery();
String[] param = query.split("&");
String id = null;
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
return id;
}
}
youtube_video_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/webvideo_layout2"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
>
<ImageView
android:id="#+id/img_thumnail"
android:layout_width="250dp"
android:layout_height="180dp"
android:layout_centerInParent="true"
android:scaleType="fitXY" />
<ImageView
android:id="#+id/iv_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/icn_play" />
</RelativeLayout>
</LinearLayout>

Try this
public static String getYoutubeThumbnailUrlFromVideoUrl(String videoUrl) {
return "http://img.youtube.com/vi/"+getYoutubeVideoIdFromUrl(videoUrl) + "/0.jpg";
}
public static String getYoutubeVideoIdFromUrl(String inUrl) {
inUrl = inUrl.replace("&feature=youtu.be", "");
if (inUrl.toLowerCase().contains("youtu.be")) {
return inUrl.substring(inUrl.lastIndexOf("/") + 1);
}
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(inUrl);
if (matcher.find()) {
return matcher.group();
}
return null;
}

This might help someone. The idea is to first get the videos you want, Here I've retrieved a list of videos from a playlist. After that i used this class:
http://blog.blundell-apps.com/imageview-with-loading-spinner/
To display a progress bar while the thumbnail was being retrieved from the web.
/***
* Fetch all videos in a playlist
* #param playlistId
* #return
* #throws ClientProtocolException
* #throws IOException
* #throws JSONException
*/
public YouTubePlaylist fetchPlaylistVideos(String playlistId) throws ClientProtocolException, IOException, JSONException {
String playlistUrl = "https://gdata.youtube.com/feeds/api/playlists/" + playlistId + "?v=2&alt=jsonc";
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(playlistUrl);
HttpResponse response = client.execute(request);
String jsonString = GeneralHelpers.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
if (jsonString.contains("Playlist not found")) {
Log.e(TAG, "playlist not found. id: " + playlistId);
return null;
}
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
String playlistTitle = json.getJSONObject("data").getString("title");
String author = json.getJSONObject("data").getString("author");
List<YouTubeVideo> videos = new ArrayList<YouTubeVideo>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject video = jsonArray.getJSONObject(i).getJSONObject("video");
// The title of the video
String title = video.getString("title");
String url;
try {
url = video.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = video.getJSONObject("player").getString("default");
}
String thumbUrl = video.getJSONObject("thumbnail").getString("sqDefault");
String videoId = video.getString("id");
String uploaded = video.getString("uploaded");
String duration = video.getString("duration");
String minutes = (Integer.parseInt(duration) / 60 < 10) ? "0" + (Integer.parseInt(duration) / 60) : "" + (Integer.parseInt(duration) / 60);
String seconds = (Integer.parseInt(duration) % 60 < 10) ? "0" + (Integer.parseInt(duration) % 60): "" + (Integer.parseInt(duration) % 60);
duration = minutes + ":" + seconds;
videos.add(new YouTubeVideo(title, author, url, thumbUrl, videoId, uploaded, duration));
}
YouTubePlaylist playlist = new YouTubePlaylist(author, playlistId, playlistTitle, videos);
return playlist;
}//end fetchPlaylistVideos

Related

How to search for images in Android Programmatically?

I have some EditTexts in my Activity.First text the for the title, second is for author.Now the user loose focus from the second edittext ie author.I want to get the images related to that content (title and author).So what I did, I concat the title and author name and make HTTP request using Volley.And I print that response.But the response is so unpredictable that I can not fetch the images from it.
try {
String googleImageUrl = "http://images.google.com/images?q=";
String query = URLEncoder.encode(title + " " + author, "utf-8");
String url = googleImageUrl + query;
Toast.makeText(context, url, Toast.LENGTH_SHORT).show();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
post_des.setText("Response is: " + response);
Log.i("Show me something awesome dude", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
post_des.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
And the responce is like this:
Response is: <!doctype html><html itemscope="" itemtype="http://schema.org/SearchResultsPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon"><title>something something - Google Search</title><style>#gb{font:13px/27px Arial,sans-serif;height:30px}#gbz,#gbg{position:absolute;white-space:nowrap;top:0;height:30px;z-index:1000}#gbz{left:0;padding-left:4px}#gbg{right:0;padding-right:5px}#gbs{background:transparent;position:absolute;top:-999px;visibility:hidden;z-index:998;right:0}.gbto #gbs{background:#fff}#gbx3,#gbx4{background-color:#2d2d2d;background-image:none;_background-image:none;background-position:0 -138px;background-repeat:repeat-x;border-bottom:1px solid #000;font-size:24px;height:29px;_height:30px;opacity:1;filter:alpha(opacity=100);position:absolute;top:0;width:100%;z-index:990}#gbx3{left:0}#gbx4{right:0}#gbb{position:relative}#gbbw{left:0;position:absolute;top:30px;width:100%}.gbtcb{position:absolute;visibility:hidden}#gbz .gbtcb{right:0}#gbg .gbtcb{left:0}.gbxx{display:none........like wise
I was expecting to get a Html doc.
So how to make a HTTP request for images with the content(title and author).
Edit
In layman language,
Suppose I am on images.google.com, and I typed in something in search bar, and make a search, now I want the data that Google return as the Url of the images on that webpage(I am doing all this in backend not showing it to the user.)
I think it is now understandable :)
You got html but of the whole search page. You can retrieve pictures' urls with css selectors and [JSOUP library][2] (easy to use). Just go to Chrome browser and then choose Settings - More tools - Developer tools. Then click the right mouse button on a picture and choose inspect and you'll see which container is for the pictures and what div contains src url of the images and then you right click this div and choose copy css selector. Then work with the library.
But be aware, it's not practical cause if they change the page html your code will beak. You better use specific api for this purpose, like Google Custom Search API as it was suggested in comments above.
To put image into UI you need to get its url address and then you can use Glide or Picasso or even Volley
// Retrieves an image with Volley specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
EDIT:
Here is CSS selector for all images on the google search page img.rg_ic. Using Jsoup and this selector you'll get access to all the image tags on the page
Jsoup example:
Document doc = Jsoup.connect(your link string).get();
Elements imgs = doc.select("img");//the selector
for (Element img : imgs) {
//add img urls to String array and then use to get imgs with them
String s = img.attr("src");
arr.add(s);
}
[![enter image description here][3]][3]
EDIT2 :
Your code with changes:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
TextView textView;
String googleImageUrl = "https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=";
ArrayList<String> urls = new ArrayList<>();
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Log.i("someething" , "something");
getImages("https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=somethingsomething");
}
});
}
private void getImages(String url) {
Document doc = null;
try{
doc = Jsoup.connect(url).get();
}catch (IOException e){
e.printStackTrace();
}
Elements imgs = doc.select("img");
System.out.println("Damn images"+imgs);
for (Element img : imgs){
Log.d("image-src", img.attr("data-src"));//changed `src` to `data-src`
}
}
}
You can get a List of google search images using Jsoup .،. see official site here https://jsoup.org/
/**
* Extract images from google as ArrayList.
*
* #param searchQuery is the string to search for
* #return returnedURLS is the List of urls
*/
private List<String> extractImagesFromGoogle(String searchQuery) throws IOException {
final String encodedSearchUrl = "https://www.google.com/search?q=" + URLEncoder.encode(searchQuery, "UTF-8") + "&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUpP35yNXiAhU1BGMBHdDeBAgQ_AUIECgB";
Document document = Jsoup.connect(encodedSearchUrl).get();
String siteResponse = document.toString();
List<String> returnedURLS = new ArrayList<String>();
// parse the object and query the values (the urls) for specific keys ("ou")
Pattern pattern = Pattern.compile("\"ou\":\"(.*?)\"");
Matcher matcher = pattern.matcher(siteResponse);
while (matcher.find()) {
returnedURLS.add(matcher.group(1));
}
return returnedURLS;
}
// Test it now:
List<String> retrievedURLS = new ArrayList<String>();
try {
retrievedURLS = extractImagesFromGoogle("pyramids");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(">> List Size: " + retrievedURLS.size());
System.out.println(">> List of images urls: " + retrievedURLS);

How to improve image uploading and downloading time on google cloud bucket

I am uploading & downloading files in bucket created on Google Cloud through Project created in Android-Studio.
I am feeling that images upload and download is taking long time.
I have also checked it by enabling automatic scaling, my appengine-web.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>APP_ID</application>
<version>1</version>
<threadsafe>true</threadsafe>
<instance-class>F4_1G</instance-class>
<automatic-scaling>
<min-idle-instances>1</min-idle-instances>
<!-- ‘automatic’ is the default value. -->
<max-idle-instances>automatic</max-idle-instances>
<!-- ‘automatic’ is the default value. -->
<min-pending-latency>30ms</min-pending-latency>
<max-pending-latency>automatic</max-pending-latency>
<max-concurrent-requests>50</max-concurrent-requests>
</automatic-scaling>
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
<property name="gcm.api.key" value="gcm_key" />
</system-properties>
</appengine-web-app>
And Servlet to Upload image looks like this:
public class UploadImageServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(UploadImageServlet.class.getName());
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
ServletFileUpload upload = new ServletFileUpload();
resp.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
ImageJson data = new ImageJson();
byte[] image = null;
byte[] imageThumbnail = null;
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
String field = item.getFieldName();
String value = IOUtils.toString(stream);
try {
if (field.equalsIgnoreCase(SESSION_PARAM_IN_FORM)) {
data.session = value;
} else if (field.equalsIgnoreCase(USER_PARAM_IN_FORM)) {
data.user = Long.parseLong(value);
}
} catch (NumberFormatException e) {
logger.warning("Invalid " + field);
}
// user, session
} else {
logger.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
data.imageName = item.getName();
// You now have the filename (item.getName() and the
// contents (which you can read from stream). Here we just
// print them back out to the servlet output stream, but you
// will probably want to do something more interesting (for
// example, wrap them in a Blob and commit them to the
// datastore).
image = IOUtils.toByteArray(stream);
System.out.println("Creating Thumbnail...");
ImagesService imagesService = ImagesServiceFactory.getImagesService();
Image oldImage = ImagesServiceFactory.makeImage(image);
Transform resize = ImagesServiceFactory.makeResize(120, 120);
//Resize The Image using the transform created above
Image resizedImage = imagesService.applyTransform(resize, oldImage);
imageThumbnail = resizedImage.getImageData();
System.out.println("Thumbnail created!!");
}
}
resp.getWriter().write(new Gson().toJson(saveImage(data, image, imageThumbnail)));
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
You must upload and download images using Json format.
If you want to know any more, please contact me
Hope will be helpfull

Extract a youtube video url from a site url using jsoup

I had this code working for the same site but they changed the theme and now i'm struggling. What could i be doing wrong here to get the url of the youtube video? Here's my approach. The example link of the site is http://kabumbu.co.tz/mahojiano-na-masau-bwire/
Element video = doc.select("div.single-archive iframe").first() ;
videourl = video.attr("src");
The code is correct so far but I just was wrongly extracting the video id from the video url. Using this method worked
public static String extractVideoId(String ytUrl) {
String vId = null;
Pattern pattern = Pattern.compile(".*(?:youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=)([^#\\&\\?]*).*");
Matcher matcher = pattern.matcher(ytUrl);
if (matcher.matches()){
vId = matcher.group(1);
}
return vId;
}
Alternatively, here is a Jsoup only solution:
/**
*
* /!\ Exceptions raised by this method are NOT logged. /!\
*
* #param youtubeUrl
* #return videoId or null if an exception occured
*
*/
public static String extractVideoId(String youtubeUrl) {
String videoId = null;
try {
Document videoPage = Jsoup.connect(youtubeUrl).get();
Element videoIdMeta = videoPage.select("div[itemtype=http://schema.org/VideoObject] meta[itemprop=videoId]").first();
if (videoIdMeta == null) {
throw new IOException("Unable to find videoId in HTML content.");
}
videoId = videoIdMeta.attr("content");
} catch (Exception e) {
e.printStackTrace(); // alternatively you may log this exception...
}
return videoId;
}
The Best Way is
code =youtubeUrl.substring(youtubeUrl.length() - 11);

JSON parsing not encoding string with underscore in Android using Volley

I am trying to encode a string which contains a URL, I have a strange issue where the complete string is not being returned, I have noticed that it may be related to the underscore, I have tried a few solution where I replace the underscore, but haven't had much luck with that solution. Below is the JSON.
[{"id":"1","source":"BBC WORLD NEWS",
"time_date":"Sat, 25 Oct 2014 10:49:13",
"title":"Iran hangs woman despite campaign","description":"Iran defies an international campaign and hangs a woman who killed a man she said was trying to sexually abuse her.",
"link":"http:\/\/www.bbc.co.uk\/news\/world-middle-east-29769468#sa-ns_mchannel=rss&ns_source=PublicRSS20-sa",
"image":"http:\/\/news.bbcimg.co.uk\/media\/images\/78529000\/jpg\/_78529517_78528720.jpg"},
I am trying to retrieve the image element from the json. The following is what I receive from my parsing.
http://news.bbcimg.co.uk/media/images/78526000/jpg
I am using this code at the moment:
String imageurl = feed.getImage();
try {
imageurl = URLDecoder.decode(imageurl, "UTF-8");
System.out.println("---------------------------"+imageurl);
imageurl.replace("_", "%5f");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
getimage method:
private String image;
public String getImage() {
return image;
}
private void requestNewsData(String uri) {
RestAdapter api = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
NewsAPI restapi = api.create(NewsAPI.class);
restapi.news(new Callback<List<RssObject>>() {
public void success(final List<RssObject> newsFeed, Response response) {
Log.v("nas", "the webservice success " + response.getReason());
for (int i = 0; i < newsFeed.size(); i++) {
System.out.println(newsFeed.get(i).description);
newsList.add(newsFeed.get(i).description);
FeederModel feed = new FeederModel();
feed.setSource(newsFeed.get(i).source);
feed.setImage(newsFeed.get(i).image); // adding setimage
}
}
The retrieved string is missing the final part of the url.
Any suggestion would be gratefully appreciated. Thanks.

Android post image using MultipartEntity

I'm trying to upload multiple images to a PHP server along with a few other parameters (strings), using the POST method. I'm using Multipart method. I added 4 libraries prescribed in various solutions (apachemime, httpclient, httpmime, httpcore), but my SDK doesn't recognise MultipartEntity, displaying the error: 'cannot be resolved to a type'. I've also tried MultipartEntityBuilder, but even that's showing the same error. I basically want to upload a Bitmap Arraylist to the server & show a progress bar simultaneously.
You should post some code with the issue so we can take a look and help you.
But if you want to try something a little bit simple you can use this library, AsyncHttpClient: http://loopj.com/android-async-http/
Using this library you could post multiple files like this:
private static AsyncHttpClient clientHttp = new AsyncHttpClient();
...
RequestParams params = new RequestParams();
final String TAG_FILE = "archivo1";
final String TAG_FILE_1 = "archivo2";
final String TAG_FILE_2 = "archivo3";
final String PATH_FILE_1 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file1.jpg";
final String PATH_FILE_2 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file2.jpg";
final String PATH_FILE_3 = ApplicationContext.getInstance().getFilesDir().getPath() + "/" + "file3.jpg";
try {
params.put(TAG_FILE, PATH_FILE_1);
params.put(TAG_FILE_1, PATH_FILE_2);
params.put(TAG_FILE_2, PATH_FILE_3);
params.put(TAG_PARAM, "SOME TEXT");
}
catch(FileNotFoundException e) {
//Manage your exception
}
final int DEFAULT_TIMEOUT = 30 * 1000;
clientHttp.setTimeout(DEFAULT_TIMEOUT);
clientHttp.post("http://somereceiver.php", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
//Do your code on success
}
#Override
public void onStart() {
// Show your progress bar
}
#Override
public void onFinish() {
// Hide your progress bar
super.onFinish();
if(PATH_FILE_1 != null) {
File tem = new File(PATH_FILE_1);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_2 != null) {
File tem = new File(PATH_FILE_2);
if(tem.exists()) tem.delete();
}
if(PATH_FILE_3 != null) {
File tem = new File(PATH_FILE_3);
if(tem.exists()) tem.delete();
}
}
});
You could also use the generic response type if you dont need json, so you get a string.
Hope this helps.

Categories

Resources