thumbnail video from url using image? - java

I already success display thumbnail video from URL on my android app when internet connection is connected, but when internet connection is off the thumbnail doesn't display.
here is my code.
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail("http://somedomain.com/video/myvideo.mp4", Thumbnails.MICRO_KIND );
imgPhoto.setImageBitmap(bmThumbnail);
i want the thumbnail still display although connection is off,there is away to achieve like save the cache on sdcard first, like image cache does? or any other solution to show thumbnail video when internet connection is off?
thanks,

public static String getBitmapFromURL(final Activity activity, String link,
String filename) throws FileNotFoundException,
MalformedURLException, IOException {
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
File file = null;
file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ CommonVariable.KCS_IMAGE_FOLDER_NAME_PHONE_MEMORY);
// have the object build the directory structure, if needed.
if (!file.exists()) {
file.mkdirs();
}
// create a File object for the output file
File outputFile = new File(file, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedOutputStream out = new BufferedOutputStream(fos, 1024);
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
out = new BufferedOutputStream(fos, 1024);
int b;
while ((b = input.read()) != -1) {
out.write(b);
}
out.close();
connection.disconnect();
return outputFile.getAbsolutePath();
}
use this function,it will return string of sdcard path.and use this path u can set bitmap image using below function:
public static void setImagesNew(ImageView img, String pathName,
Activity activity) {
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(pathName, Thumbnails.MICRO_KIND );
img.setImageBitmap(bmThumbnail);
bmp = null;
System.gc();
Runtime.getRuntime().gc();
}
i hope this is useful to you...............

Related

Copying Image from URL to HTTP URL

Someone is providing a S3 Presigned URL so that I can upload my images to that link. All my images are on the website. Is there a way in JAVA to copy the image URL to the new URL provided ?
I am trying to do this. Seems like an overkill
try {
// Get Image from URL
URL urlGet = new URL("http://something.com/something.png");
BufferedImage image = ImageIO.read(urlGet);
//for png
ImageIO.write(image, "png",new File("/something.png"));
// for jpg
//ImageIO.write(image, "jpg",new File("/something.jpg"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
outputStream.flush();
byte[] imageInBytes = outputStream.toByteArray();
outputStream.close();
URL url = new URL(putUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod(HttpMethod.PUT);
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, PNG_MIME_TYPE);
OutputStream stream = connection.getOutputStream();
try {
stream.write(imageInBytes);
} finally {
stream.close();
connection.disconnect();
}
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
return "";
default:
break;
}
} catch (Exception e) {
log.error("Exception occured", e);
throw e;
}
There would be no point converting to BufferedImage and back for the copy when you can preserve the byte stream of the original files. The first part can be replaced with simple call to extract the bytes off your website:
byte[] imageInBytes = read(urlGet);
Where read() is:
private static byte[] read(URL url) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(16*1024);
try (var in = url.openStream()) {
in.transferTo(out);
}
return out.toByteArray();
}
If you use JDK11 onwards you could try the HttpClient class for the GET and POSTs, for example this does same as above if passing it urlGet.toURI():
private static byte[] read(URI uri) throws IOException, InterruptedException
{
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
var resp = client.send(request, BodyHandlers.ofByteArray());
return resp.body();
}

HTTPUtils deprecated .. what do I do instead?

I need to download icons from the OpenWeatherMap website, build a URL, download the image, save it to local storage and also check to see if they already exist. HTTPUtils is underlined in red and when I looked it up, it's no longer being used. The Bitmap code was given to use by the professor.
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(TEMPS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//this is what talks to the xml on the website
xpp.setInput(inputStream, "UTF-8");
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("temperature")) {
curr = xpp.getAttributeValue(null, "value");
//tell android to call onProgressUpdate with 25 as parameter
publishProgress(25);
min = xpp.getAttributeValue(null, "min");
publishProgress(50);
max = xpp.getAttributeValue(null, "max");
publishProgress(75);
} else if (xpp.getName().equals("weather")) {
icon = xpp.getAttributeValue(null, "icon");
}
}
xpp.next();
}
//Start of JSON reading of UV factor:
//create the network connection:
URL UVurl = new URL(UV);
HttpURLConnection UVConnection = (HttpURLConnection) UVurl.openConnection();
inputStream = UVConnection.getInputStream();
//create a JSON object from the response
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
//now a JSON table:
JSONObject jObject = new JSONObject(result);
double aDouble = jObject.getDouble("value");
Log.i("UV is:", ""+ aDouble);
uv = aDouble;
//*****This is where I need help
Bitmap image = null;
URL imageUrl = new URL(IMAGE);
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
image = BitmapFactory.decodeStream(connection.getInputStream());
}
image = HTTPUtils.getImage(IMAGE);
FileOutputStream outputStream = openFileOutput(icon + ".png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
outputStream.flush();
outputStream.close();
public boolean fileExistance(String weatherIcons){
File file = getBaseContext().getFileStreamPath(weatherIcons);
return file.exists();
Log.i("File name:", ""+ file);
}
FileInputStream fis = null;
try {
fis = openFileInput("C:/Users/kathy/AndroidStudioProjects/AndroidLabs/app/src/main/res/drawable");
} catch (FileNotFoundException e) {
Log.e("Download this file", e.getMessage());
}
Bitmap bm = BitmapFactory.decodeStream(fis);
publishProgress(100);
Thread.sleep(2000); //pause for 2000 milliseconds to watch the progress bar grow
} catch (Exception ex) {
}
return null;
}
While I don't really understand which package HTTPUtils comes from, I think relying on the standard classes from the JDK and Android SDK is the way to go.
try {
// Get an open Stream to the image bytes
final InputStream stream = new URL(IMAGE).openStream();
// Wrap the Stream in a buffered one for optimization purposes
// and decode it to a Bitmap
try (final InputStream bufferedInputStream = new BufferedInputStream(stream)) {
final Bitmap image = BitmapFactory.decodeStream(bufferedInputStream);
// Process the image
}
} catch (final IOException e) {
// Handle the Exception
}
You might want to extract an helper method, which simply returns the instantiated Bitmap variable.

Java: How to convert com.google.api.services.drive.model.File to InputStream?

I am new to google drive integration.
I saved an image in google drive and I got that file by below method.
File file = getDriveService().files().get(fileId).execute();
Now when I tried to convert this file into InputStream and write this InputStream in HttpResponse then the file returns but the image is not displayed.
public InputStream convertGoolgeFileToInputStream( String fileId ) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
getDriveService().files().get(fileId).executeAndDownloadTo(outputStream);
InputStream in = new ByteArrayInputStream(outputStream.toByteArray());
return in;
//return getDriveService().files().get(fileId).executeAsInputStream();
}
You may want to try checking the download example Drive sample
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
}

Saving image by url to internal storage

Please, need help. I'm having this error java.io.FileNotFoundException: http://news.yandex.ru/quotes/1507.png (can be seen by browser) while saving it to my internal storage.
this is my method:
void downloadGraph(String link){
try {
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File dbDirectory = new File(mctx.getFilesDir().getAbsolutePath()+ File.separator+"yqimages/");
if(!dbDirectory.exists())dbDirectory.mkdir();
String fname=link.substring(link.lastIndexOf("/")+1,link.length());
File file = new File(dbDirectory, fname);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
Can you write a method to download\save this specific image (shown above)? Any help is appreciated!
Get it!! the problem is not in the code, it's in the image https://news.yandex.ru/quotes/1507.png. For some reason this picture can't be saved while the other ones do. Has it something to do with "httpS://"?
here explain all about download and save images in android.
And don't forget to add permission in Manifest for read and write external memory file.
// ist put the permission in Manifest.xml hte permission are below
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
private void saveimage() {
bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
String time = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(System.currentTimeMillis());
File path = Environment.getExternalStorageDirectory();
File dir = new File(path+"/Gallery");
dir.mkdir();
String imagename = time+".PNG";
File file = new File(dir,imagename);
OutputStream out;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
out.flush();
out.close();
Toast.makeText(Show_Online.this, "Image Save To Gallery",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(Show_Online.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

Returning Profile Picture Bitmap. Facebook Java

I have Facebook graph requests working and seem to have no problem whatsoever, However I have been trying for a while to retrieve the profile picture. But everytime I run it the bitmap seems to turn out null.
public static Bitmap DownloadImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("IMAGE", "Error getting bitmap", e);
}
return bm;
}
For Example, If I feed it this string:
String testString = "graph.facebook.com/849993771766163/picture?type=large";
The bitmap will return null every single time..
What am I doing wrong? I suspect I am getting the url wrong but I have tried everything
Try replacing
bm = BitmapFactory.decodeStream(bis);
with
bm = Bitmap.createBitmap(BitmapFactory.decodeStream(bis));
You may also need to create a scaled bitmap first and then set it to your final bitmap before setting it to a view.

Categories