Send an image from url as a attachment email in android - android

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

Related

Sending GIF image in asset folder to another application using Intent

How do we send GIF image which is present in asset folder to another application using Intent?
I have tried this:
private File getEmojiFile(int position) {
AssetManager assetManager = getApplicationContext().getAssets();
File file = new File(getCacheDir(), mEmojiFileNames[position]);
try {
if (!file.createNewFile()) {
//Emoji File already exists.
return file;
}
} catch (IOException e) {
e.printStackTrace();
}
FileChannel in_chan = null, out_chan = null;
try {
AssetFileDescriptor in_afd = assetManager.openFd(mEmojiFileNames[position]);
FileInputStream in_stream = in_afd.createInputStream();
in_chan = in_stream.getChannel();
FileOutputStream out_stream = new FileOutputStream(file);
out_chan = out_stream.getChannel();
in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
} catch (IOException ioe) {
Log.w("copyFileFromAssets", "Failed to copy file '" + mEmojiFileNames[position] + "' to external storage:" + ioe.toString());
} finally {
try {
if (in_chan != null) {
in_chan.close();
}
if (out_chan != null) {
out_chan.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return file;
}
and then sending it to another app using Intent:
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EMOJI_IMAGE_TYPE emojiImageType = getImageType(position);
intent.setType("image/gif"));
intent.setPackage(getCurrentAppPackage(SoftKeyboard.this, getCurrentInputEditorInfo()));
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
//Save emoji file because current input field supports GIF/PNG.
File emojiFile = getEmojiFile(position);
Uri photoURI = FileProvider.getUriForFile(SoftKeyboard.this, SoftKeyboard.this.getApplicationContext().getPackageName() + ".provider", emojiFile);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
dialog.dismiss();
hideWindow();
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(SoftKeyboard.this,"This text field does not support "+
"GIF"+" insertion from the keyboard.",Toast.LENGTH_LONG).show();
}
However, after this blank image is coming. Here is tried to send the image to messenger application. It accepted intent but showed blank transparent image:
Scenario: You have a gif file in the Drawable Folder.
Then the code will be:`
private void shareDrawable(Context context,int resourceId,String fileName) {
try {
//create an temp file in app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".gif");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
//Saving the resource GIF into the outputFile:
InputStream is = getResources().openRawResource(resourceId);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int current = 0;
while ((current = bis.read()) != -1) {
baos.write(current);
}
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(baos.toByteArray());
//
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/gif");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG);}
}

what is different bitmap compress option in Android webview

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..

Receive a plain text instead of image

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.

Save Image from res/drawable to Image Gallery Android

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();
}
}
}

Android, can't read images I saved to data folder

My app uses the following piece of code to write out images I have resized into the app's data folder:
private void writeImage(Bitmap bmp, String filename)
{
try
{
FileOutputStream stream = openFileOutput(filename, MODE_WORLD_WRITEABLE);
bmp.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am able to read them in a file browser (ddms) and can confirm they appear to have been written.
However, any attempt to load the images results in non-null bitmaps with width and height of -1. I am using the following code to load them:
imageList = getFilesDir().list();
Bitmap bmp = null;
for(String img : imageList)
{
try {
bmp = BitmapFactory.decodeStream(openFileInput(img));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: On further inspection, it seems, after conversion the images are of density 160 (and not 240 as they should be) also, after testing a working application it seems the -1 mWidth and -1 mHeight on the bitmaps is irrelevent.
I had same problem.my data folder given smallest image.and cursor return null pointer exception on my getDestination method.then i fixed like it
public void captureNewPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
targetUri = Uri.fromFile(targetFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 12);
}
And i use like in onActivityResult();
BitmapFactory.Options options = new BitmapFactory.Options();
networkBitmap = BitmapFactory.decodeFile(targetUri.getPath(),
options);
//ImageDialog(networkBitmap);
//String path = getRealPathFromUri(this, Uri.parse(targetUri.getPath()));
String myDeviceModel = android.os.Build.MODEL;
deviceName = Build.MANUFACTURER;
if (myDeviceModel.equals("GT-I9500")) {
} else if (deviceName.contains("samsung")) {
} else {
exif = ReadExif(targetUri.getPath());
if (exif.equals("6")) {
matrixx.postRotate(90);
} else if (exif.equals("7")) {
matrixx.postRotate(-90);
} else if (exif.equals("8")) {
matrixx.postRotate(-90);
} else if (exif.equals("5")) {
matrixx.postRotate(-90);
}
//matrixx.postRotate(-90);
}
networkBitmap = Bitmap.createBitmap(networkBitmap, 0, 0, networkBitmap.getWidth(), networkBitmap.getHeight(), matrixx, true);
Log.e("Taget File ", "Size " + targetFile.length());
if (networkBitmap != null) {
ImageSetting(networkBitmap, System.currentTimeMillis() + filename);
}
public void ImageSetting(Bitmap imageBitmap, final String fileName) {
networkBitmap = imageBitmap;
organizator(networkBitmap, fileName);
networkBitmap = null;
}` public void tamamlandiOndenFoto(Bitmap turnedBitmap, String filename) {
frontFotoFile = storeBitmap(networkBitmap, filename);
ondenFotoPath = ondenFoto.getAbsolutePath();
ondenFotoImageView.setImageBitmap(turnedBitmap);
}`
public File storeBitmap(Bitmap bp, String fileName) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dest = new File(sd, fileName);
if (bp != null) {
try {
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Alinan hata ", " Catch hata ", e);
}
return dest;
} else {
return null;
}
}
I hope give you any idea for your problem.

Categories

Resources