Crop image from URL - android

I have the following:
A very long URL of where the image is located (on the internet)
String imageAddress = data.getExtras().get("imageHTTP").toString();
The returns fine and there is an image ending with .jpg
The next part is where I'm having problems.
Basically I've got a crop intent that accepts Uri's but the following doesn't work:
Uri imageUri = Uri.parse(imageAddress);
Intent intent = new Intent(this, com.android.camera.CropImage.class);
intent.setData(uri);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP);
Any ideas?
Following error code:
got exception decoding bitmap
java.lang.NullPointerException
at com.android.camera.Util.makeInputStream(Util.java:337)

I figured this out. Was easier to save it to sdcard temporary then crop, then delete the temporary one. After that I ran it though a downloaded crop library (don't know where downloaded it from but there are a few).
File file = null;
try {
URL myImageURL = new URL(imagePath);
HttpURLConnection connection = (HttpURLConnection)myImageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
// Get the bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
// Save the bitmap to the file
String path = Environment.getExternalStorageDirectory().toString() + "/polygonattraction/app/";
OutputStream fOut = null;
file = new File(path, "temp.png");
fOut = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (IOException e) {}
Log.w("tttt", "got bitmap");
Uri uri = Uri.fromFile(file);

Related

image from gallery is not displaying on pdf file in android

I am trying to creating pdfs from images in my Android application.
I get the image successfully and created the pdf file successfully. But When I open my pdf file, images are not displayed. I have tried many solutions on Internet but all in vain.
I am pasting my code. Kindly guide me.
First I am pasting the code for getting image from gallery
Intent myIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(myIntent,120);
Now I am pasting the code of OnActivityResult Method, in which I am getting the image and craeating a pdf file.
try {
Document doc = new Document();
if (resultCode == RESULT_OK) {
if (requestCode == 120) {
if (data.getData() != null) {
Uri uri = data.getData();
Image image = Image.getInstance(uri.toString());
FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
PdfWriter.getInstance(doc, fileOutputStream);
doc.open();
doc.add(image);
doc.close();
}
}
}
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
As you are using iText you need to create BitMap format of image and then need to add into pdf.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, <pass the uri of image>);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAbsolutePosition(470f,755f);
myImg.scaleToFit(100f,100f);
document.add(myImg);
I have solved it, The solution was to use Input Stream as follows:
Uri uri = data.getData();
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);
doc.add(image);
doc.close();

Sharing image preview is wrong

When I try to share an screenshot via the Samsung email app the preview of the image I am sending is wrong. It happens only with the Samsung email app.
Here is my code:
-------here I am taking a screenshot-----------
String mPath = "";
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + "share" + ".jpeg";
// create bitmap screen capture
View v1 = getActivity().getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
-------sending a screen shot via intent-----------
Uri imageUri = Uri.parse(sorcUrl);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent, "Share"));
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}

How to get a phone display print screen?

How to get Android OS Phone display a screenshot every minute and send it by email?
use following code to get screen shot from your mobile
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
add permission in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}

bitmap.compress from Uri resulting in OutOfMemoryError

I am trying to save a bitmap which user selects into my own App path.
Unfortunately, with very big images I get OutOfMemoryError error.
I am using the following code:
private String loadImage (Uri filePath) {
File fOut = new File(getFilesDir(),"own.jpg");
inStream = getContentResolver().openInputStream(filePath);
selectedImage = BitmapFactory.decodeStream(inStream);
selectedImage.compress(CompressFormat.JPEG, 100, new FileOutputStream(fOut));
}
Is there any way for me to save any image file of any size for an Uri to a file?
*I am not in a position to resize the image e.g. by using calculateInSampleSize method.
Is there any way for me to save any image file of any size for an Uri to a file?
Since it already is an image, just copy the bytes from the InputStream to the OutputStream:
private void copyInputStreamToFile( InputStream in, File file ) {
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
(adapted from this SO answer)

Save image to sdcard from drawable resource on Android

I'm wondering how to save an image to user's sdcard through a button click.
Could some one show me how to do it. The Image is in .png format and it is stored in the drawable directory. I want to program a button to save that image to the user's sdcard.
The process of saving a file (which is image in your case) is described here: save-file-to-sd-card
Saving image to sdcard from drawble resource:
Say you have an image namely ic_launcher in your drawable. Then get a bitmap object from this image like:
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
The path to SD Card can be retrieved using:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Then save to sdcard on button click using:
File file = new File(extStorageDirectory, "ic_launcher.PNG");
FileOutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.
Here is the modified file for saving from drawable: SaveToSd
, a complete sample project: SaveImage
I think there are no real solution on that question, the only way to do that is copy and launch from sd_card cache dir like this:
Bitmap bm = BitmapFactory.decodeResource(getResources(), resourceId);
File f = new File(getExternalCacheDir()+"/image.png");
try {
FileOutputStream outStream = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) { throw new RuntimeException(e); }
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(f), "image/png");
startActivity(intent);
// NOT WORKING SOLUTION
// Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + resourceId);
// Intent intent = new Intent();
// intent.setAction(android.content.Intent.ACTION_VIEW);
// intent.setDataAndType(path, "image/png");
// startActivity(intent);
If you use Kotlin, you can do like this:
val mDrawable: Drawable? = baseContext.getDrawable(id)
val mbitmap = (mDrawable as BitmapDrawable).bitmap
val mfile = File(externalCacheDir, "myimage.PNG")
try {
val outStream = FileOutputStream(mfile)
mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
outStream.flush()
outStream.close()
} catch (e: Exception) {
throw RuntimeException(e)
}

Categories

Resources