I share a image from social network and catch it with my app (following this link), but it catch a plain text instead of image, i try to parse to uri and url but it didn't work
void handleSendText(Intent intent) {
String sharedText2 = intent.getStringExtra(Intent.EXTRA_TEXT);
//Bn1.setText("Descargar Texto plano");
if (sharedText2 != null) { // check if is null or not
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Imgs/");
if(!folder.exists()){folder.mkdir();}// create folder
int diagonal = sharedText2.indexOf(":");
String sharedText = sharedText2.substring(diagonal + 1, sharedText2.length());
sharedText = sharedText.replace(" ", "");
if (!sharedText.startsWith("htt")) {// check if it's starts with http or not
sharedText = "https" + sharedText.substring(0, sharedText.indexOf("?"));
}
c = 1;
Bitmap bitmap = null;
Uri imageUri = Uri.parse(sharedText); // parse to uri
Time now = new Time(); // time
now.setToNow();
String nombre = "Imagen-" + now.weekDay + "-" + now.month + "-" + now.year + "-" + now.minute + "_" + now.second;// name of the image
if (imageUri != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
File file = null;
file = new File(folder.getAbsoluteFile(), nombre + ".jpg");
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
//bitmap.compress(Bitmap.CompressFormat.WEBP, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Tv1.setMovementMethod(new ScrollingMovementMethod());
Tv1.setText("Es una imagen\n" + imageUri + "\n" + file + "\nnombre:\n" + nombre); // show the name of the variables
if (bitmap == null) {
Tv1.setText(sharedText2 + "\n\nsharedtext\n" + sharedText);
} else {
Tv1.setText("SI quedo\n" + sharedText);
}
}
}
}
EXTRA_TEXT is supposed to be plain text. EXTRA_STREAM, on the other hand, is supposed to be a content: Uri (though often you will get a file: Uri instead). Presumably, the information you seek will be in EXTRA_STREAM, not EXTRA_TEXT.
Related
when I upload my captured webveiw(bitmap image), I use this :
public static void saveBitmaptoPng(Bitmap bitmap, String folder, String name) {
String ex_storage = Environment.getExternalStorageDirectory().getAbsolutePath();
// Get Absolute Path in External Sdcard
String foler_name = "/" + folder + "/";
String file_name = name + ".png";
String string_path = ex_storage + foler_name;
File file_path;
try {
file_path = new File(string_path);
if (!file_path.isDirectory()) {
file_path.mkdirs();
}
FileOutputStream out = new FileOutputStream(string_path + file_name);
**bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);**
out.close();
} catch (FileNotFoundException exception) {
Log.e("FileNotFoundException", exception.getMessage());
} catch (IOException exception) {
Log.e("IOException", exception.getMessage());
}
}
It is working well. but when I change 90 to 100 of Bitmap.CompressFormat,
I got an error whe getresponseCode
int serverResponseCode = connection.getResponseCode();
if (serverResponseCode == HttpURLConnection.HTTP_OK) {
is = new BufferedInputStream(connection.getInputStream());
} else {
is = new BufferedInputStream(connection.getErrorStream());
return null;
}
when changing from 90 to 100, process flow errorStream.... but I don't know any reasons.... even 95 is also not working well..
I want to Save Image from res/drawable to Image Gallery. I am using following code but it is doing nothing.
What is the wrong with my code ? String Drawable stands for Image Name which is there in drawable folder.
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Images");
if (!direct.exists()) {
direct.mkdirs();
}
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
try {
Bitmap bitmap = BitmapFactory.decodeResource(
context.getResources(),
context.getResources().getIdentifier(
"#drawable/" + Drawable, "drawable",
context.getPackageName()));
bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 95, bos);
byte[] bitmapdata = bos.toByteArray();
fos = new FileOutputStream(direct + "/" + "IMG-" + CurrentDateTime
+ ".jpg");
fos.write(bitmapdata);
} catch (Exception e) {
Log.e("Internal Image Save Error->", e.toString());
} finally {
try {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
fos.flush();
}
} catch (IOException ignored) {
Log.e("Internal Image Save Error->", ignored.toString());
}
}
I just found that it is saving image but It is taking some time like 10 mins.
Copy Image from Drawable to Gallery : It is giving File Not Found Exception on Input Stream. String Drawable is image name, i.e. data1
public static void downloadInternalImage(String Drawable, Context context) {
Toast.makeText(context, "Downloading Image...\nPlease Wait.",
Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Images");
if (!direct.exists()) {
direct.mkdirs();
}
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream("android.resource://"
+ context.getPackageName() + "/drawable/" + Drawable + "");
output = new FileOutputStream(direct + "/" + "IMG-"
+ CurrentDateTime + ".jpg");
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
Toast.makeText(context, "Image Saved.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("Internal Image Save Error->", e.toString());
Toast.makeText(context,
"Couldn't Save Image.\nError:" + e.toString() + "",
Toast.LENGTH_LONG).show();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ignored) {
Log.e("Internal Image Save Error->", ignored.toString());
Toast.makeText(
context,
"Couldn't Save Image.\nError:" + ignored.toString()
+ "", Toast.LENGTH_LONG).show();
}
}
}
I'm currently working on an App that receives multiple images via socket. To save them, I wrote the following methods:
public static boolean saveTempImageToGallery(Context c) {
try {
FileInputStream fis = c.openFileInput(Settings.TEMP_PHOTO_STORAGE);
// create name of file: [date]-[time]-baby
final String tFilename = new SimpleDateFormat("dd-MM-yyyy_hh-mm-ss")
.format(new Date()) + ".png";
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d(TAG, "External storage available.");
// sd card available
File dir = getExternalStorageDir("Photos");
if (dir.mkdirs() || dir.isDirectory()) {
Log.i(TAG, "Directory: "+dir.getAbsolutePath());
File newImage = new File(dir, tFilename);
if (newImage.createNewFile() && newImage.isFile()) {
Log.i(TAG, "Saving image to "+newImage.getAbsolutePath());
final Bitmap bmp = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// compress image to png
bmp.compress(Bitmap.CompressFormat.PNG, 40, baos);
FileOutputStream fo = new FileOutputStream(newImage);
fo.write(baos.toByteArray());
fo.close();
Log.i(TAG, "Image saved!");
return true;
}
} else {
Log.d(TAG, "Could not create directory.");
}
} else {
Log.d(TAG, "External storage not available.");
}
} catch (Exception e) {
}
return false;
}
public static File getExternalStorageDir() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/"
+ Settings.EXT_STORAGE_DIRECTORY);
return dir;
}
public static File getExternalStorageDir(String subdir) {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/"
+ Settings.EXT_STORAGE_DIRECTORY + "/" + subdir);
return dir;
}
After saving them, I'd like to offer the user the possibility to view them in the default gallery app. After reading some post, I adapted the following code:
MediaScannerConnectionClient mScanClient = new MediaScannerConnectionClient() {
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted", uri + "success");
if (uri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally {
if (mScanCon != null)
mScanCon.disconnect();
mScanCon = null;
}
}
#Override
public void onMediaScannerConnected() {
Log.i(TAG, "Media Scan Connected.");
String[] files = Support.getExternalStorageDir("Photos")
.list();
Log.i(TAG,
Support.getExternalStorageDir("Photos").list().length
+ " elements in dir.");
if (files.length > 0) {
for (String cur : files) {
if (cur.equals(".") || cur.equals(".."))
continue;
Log.i(TAG, "Using "
+ cur
+ " to scan stuff. "
+ Support.getExternalStorageDir("Photos")
.getAbsolutePath() + "/" + cur);
Log.i(TAG, "Not using "
+ cur
+ " to scan stuff. "
+ Support.getExternalStorageDir("Photos")
.toString() + "/" + cur);
mScanCon.scanFile(
Support.getExternalStorageDir("Photos")
.getAbsolutePath() + "/" + cur,
"image/*");
break;
}
} else {
Toast.makeText(getApplicationContext(),
"No images available.", Toast.LENGTH_LONG)
.show();
}
}
};
if (mScanCon != null)
mScanCon.disconnect();
mScanCon = new MediaScannerConnection(getApplicationContext(),
mScanClient);
mScanCon.connect();
Weird thing: Seems like onMediaScannerConnected is never fired - anyone has an idea? I've been searching the web and stackoverflow for the last hour..
Thank you.
You really don't have to connect to the media scanner to start a scan, you can use this static method instead.
MediaScannerConnection.scanFile(context, new String[] {dir.getAbsolutePath()}, null, null);
edit:
Uri uri = Uri.parse(filePath);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/*");
startActivity(i);
I have a problem that I want to send an email with Image attachment and image is on Url. I am not able to send that. Please suggest me for right result.
Thanks in advance.
Here is the code:
btn_mail.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setImage(item.getImageUrl());
if(item instanceof Product)
{
body = "<html><body>Found this a great deal on "+item.getTitle()+"<br><br><img src="+item.getImageUrl(100)+"></body></html>";
}else
{
Offer offer = (Offer)item;
body = "<html><body>Found this a great deal on "+item.getTitle()+"<br><br><img src="+item.getImageUrl(100)+"></body></html>";
}
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, item.getTitle());
/*emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"Title: " + item.getTitle() + "\n" +
"Description: " + item.getDescription() + "\n" + "\n" +
"Max Price: " + max_price + "\n" +
"Min Price: " + min_price);*/
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,Html.fromHtml(body));
//emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://com.shopzilla.android.common/" + R.drawable.barcode));
//emailIntent.putExtra(Intent.EXTRA_STREAM, imageBitmap);
emailIntent.setType("message/rfc822");
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
private void setImage(String string) {
try {
URL url = new URL(string);
imageBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The <img> tag won't work. To send the image as an attachment, you must save it to the SD card.
You'll need to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
to your AndroidManifest.xml.
To save the image, do this (in a background thread!):
try {
File rootSdDirectory = Environment.getExternalStorageDirectory();
File pictureFile = new File(rootSdDirectory, "attachment.jpg");
if (pictureFile.exists()) {
pictureFile.delete();
}
pictureFile.createNewFile();
FileOutputStream fos = new FileOutputStream(pictureFile);
URL url = new URL("http://your_image_server/dummy.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
InputStream in = connection.getInputStream();
byte[] buffer = new byte[1024];
int size = 0;
while ((size = in.read(buffer)) > 0) {
fos.write(buffer, 0, size);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
After the image is saved, get its Uri and send to the intent (in the main thread):
Uri pictureUri = Uri.fromFile(pictureFile);
emailIntent.putExtra(Intent.EXTRA_STREAM, pictureUri);
Hope it helps :)
You can do that very quickly with this code
protected Uri getImageUri(String imgTitle,Bitmap inImage) {
if(inImage == null) {
return null;
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(getContentResolver(), inImage, imgTitle, null);
return Uri.parse(path);
}
The Bitmap come from imageview and you can easy have it from
((BitmapDrawable)img.getDrawable()).getBitmap()
getImageUri has to be executed in a Thread (or Handler) in order not to block the main application behavior
my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it
so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it:
Note: i have no errors in the code // no red marks
This is all the code:
private void UpdateAds(String Bookinfo,TextView myText){
elhgsdatabase db = new elhgsdatabase(this);
if (Bookinfo != "didn't read titels"){
String debContent="";
String output ="";
int NUMBEROFFIELDS = 5;
String s = addressString;
long idx;
String [] buffer = new String[NUMBEROFFIELDS];
output = "";
int l = 0;
while (s.indexOf("[")>-1){
int fk = s.indexOf("[");
int fl = s.indexOf("]");
if(fk > -1){
buffer[l] = s.substring(fk+1, fl);
s = s.substring(fl+1);
l++;
if (l == NUMBEROFFIELDS){
//1. Query the database to check if the book exists
//---get all titles---
db.open();
Cursor c = db.getBookTitle (buffer[0]);
if (c.getCount()==1)
{ myText.setText("This Books Exist \n"); }
else if(c.getCount()==0)
{ String locLink;
locLink = getLocalLink(buffer[3], buffer[0]);
c.moveToFirst();
if (!locLink.equalsIgnoreCase("-1")){
idx= db.insertTitle(buffer[0], buffer[1], buffer[2], getDate(buffer[3]), buffer[4], locLink);
}
else { //there was a problem with retrieval-saving of the Book info locally
myText.setText("There was a problem with retrieval-saving of the Book info locally\n");
}
}//if(c.getCount()==0)
else{//The table has two Books with the same Name. Do something
myText.setText("The table has two Books with the same Name\n");
}
c.close();
l = 0;
}//if(l == NUMBEROFFIELDS)
} //if (fk>-1)
}//while
db.close();
} //of if(BookInfo...
else {
myText.setText("Nothing is Done\n");
}
}
//This method gets the local link field of the active book records
// it goes on the web, gets the content and stores it in a place
// and saves the path of that place in the database for that
//it returns -1 if something wrong happened during the process
public String getLocalLink(String image_URL, String BookName){
/** This is what we do with this method:
* Go online, according to the link, get the content, call the method to save, get the local link
* and return it
*/
setContentView(R.layout.main);
reviewImageLink = image_URL;
URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
try {
reviewImageURL = new URL(reviewImageLink);
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
new DownloadImageTask().execute(reviewImageURL);
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
.getString(R.string.directory));
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");
}
} catch (MalformedURLException e) {
Log.v(TAG, e.toString());
}
return ("/sdcard/Hanud/"+BookName+".jpg");
}
private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
protected Bitmap doInBackground(URL... paths) {
URL url;
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);}
else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
}
else {read = is.read(imageData, downloaded, buffersize);}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
public void saveToSDCard(Bitmap bitmap, String name) {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.v(TAG, "SD Card is available for read and write "
+ mExternalStorageAvailable + mExternalStorageWriteable);
saveFile(bitmap, name);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.v(TAG, "SD Card is available for read "
+ mExternalStorageAvailable);
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.v(TAG, "Please insert a SD Card to save your Video "
+ mExternalStorageAvailable + mExternalStorageWriteable);
}
}
private void saveFile(Bitmap bitmap, String name) {
String filename = name;
ContentValues values = new ContentValues();
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
sdImageMainDirectory.mkdirs();
File outputFile = new File(sdImageMainDirectory, filename);
values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.DATE_ADDED, System
.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
Uri uri = this.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
try {
OutputStream outStream = this.getContentResolver()
.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean hasExternalStoragePublicPicture(String name) {
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
File file = new File(sdImageMainDirectory, name);
if (file != null) {
file.delete();
}
return file.exists();
}
public void showAllBooks( )
{
final elhgsdatabase db = new elhgsdatabase(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Get new entry
db.open();
long currTime = System.currentTimeMillis();
String p_query = "select * from ads where timeFrom<=?";
Cursor c = db.rawQuery(p_query, new String[] { Long.toString(currTime)});
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}, 5000); // 5000 miliseconds
}
public long getDate(String s){
String[] formats = new String[] {
"yyyy-MM-dd HH:mm:ss"
};
SimpleDateFormat sdf=null;
String st;
for (String format : formats) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("EST"));//UTC or EST
st = new String(sdf.format(new Date(0)));
System.err.format(format, st);
}
Calendar c = Calendar.getInstance();
Date dt;
try {
dt = sdf.parse(s);
c.setTime(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c.getTimeInMillis() ;
}
public void DisplayTitle(final Cursor c)
{
Toast.makeText(this,
"Title: " + c.getString(0) + "\n" +
"isbn: " + c.getString(1) + "\n" +
"Publisher: " + c.getString(2) + "\n" +
"Year: " + c.getString(3) + "\n" +
"Image On Line: " + c.getString(4) + "\n" +
"Image On SD " + c.getString(5) + "\n" ,
Toast.LENGTH_LONG).show();
String imageInSD = c.getString(5);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
myImageView=(ImageView)findViewById(R.id.imageview1);
myImageView.setImageBitmap(bitmap);
}
----------
I'm pretty sure you're setting the second image name to the reviewImageLink (not sure if this is a class variable or what) variable. Instead, try passing both the URL and the String to the AsyncTask. Instead of passing a URL... pass in an Object... where the first one is the URL and the second is the name, and use that in the onPostExecute.
You don't show how ImageLink is set up. But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here.