Android: fetch and save image to SD card using local web files - java

I want to get a web page (html, php?, javascript?) stored on my Android phone's SD card, to get an image from a specified url and save it back to the SD card.
Is this possible and if so in what language can this be achieved? Any help would be much appreciated even if you can just say yes and point me in the right direction. I'm happy to tinker around with code but don't even know where to start or if this is simply not possible.
Thanks

If you have url to get image then this code will help you
String myfeed="your url";
URL url;
try {
url = new URL(myfeed);
InputStream content = (InputStream)url.getContent();
d = Drawable.createFromStream(content , "src");
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
String path = Images.Media.insertImage(getContentResolver(),bitmap,mImageName, null);
screenshotUri = Uri.parse(path);
System.out.println("your path :"+screenshotUri);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

how to send a file with a picture from the app to e-mail or whatsapp (25.10.2021)

I have tried about 10 answers to a similar question, but none of them were successful. Something might be out of date. Please give an answer for today.
Simple task:
I want my app to be able to send a file with an image to e-mail or whatsapp.
I put the file with the image in the application resources in the folder Drawable.
Its size is 5 MB.
How to do this in Java?
I'm asking for code, not links to similar answers. I've tried most of them already.
Some decisions came to null.bin.
Some don't send anything at all and throw an error.
Perhaps I am not specifying any permissions.
Something else is possible.
I'm new.
I would like an answer with comments (what I am writing and why)
// step 1. I put the picture in the folder Drawable
// clicking on the button sends the picture through the messenger to other users
public void onClick_sendMyImage(View v) {
// Step 2.Convert PICTURE to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
saveImage(bitmap); // 3. save the PICTURE in the internal folder
send(); // 4.sending PICTURE (function code below)
}
// step 3. Saving the image in the internal folder:
private static void saveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
//Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "image_test" + ".jpg";
File file = new File(myDir, fname);
if(file.exists()) file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Step 4. Sending the saved PICTURE
public void send(){
try{
File myFile = new File("/storage/emulated/0/saved_images/image_test.jpg");
// for something I create this type (so it is said in one of the answers)
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(type);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(myFile));
Intent intent1 = Intent.createChooser(intent, "what do you want to send ?");
startActivity(intent1);
}catch (Exception e){
Toast.makeText(this, "repeat sending", Toast.LENGTH_SHORT).show();
}
}
Sending an image from an app turned out to be not a good idea.
The image cannot be edited if necessary.
Over time, you may want to add more images, etc..
I did it differently, and it turned out better:
I put the image on GoogleDisk.(now I can change it at any time without having
to ask users to reinstall the application every time the picture changes).
I placed a link to the picture in the FireBase Database. (I also placed a banner with a picture here.).
I connected the application to the Firebase Database.
In the activity I made a RecyclingView, where I get a banner(s) and a link(s) to the original image(s). The user can download this link or send it through whatsapp anywhere and download the original picture in good quality (A1, 2.5Mb).
thanks, guys..
I thank the guys for the tips, especially mr.Blackapps. In this case, you really can't do without a FileProvider.

How to set a standard image to show if a search for associated image name yields no results?

I am working on a project for my course and have been asked to show an associated image for products in a system, the user can add products, and he enters the name of the image file whilst doing so. the program then finds the image file and displays it with the product information.
I would like to add some additional code so that if there is no image file matching the string input that a standard image is shown. The code I have so far either shows the image file if it is found or does not show anything. can someone show me how to modify it so that it can show a standard image if no associated image file is found. the standard image is simply "no-image-found.jpg". Here is the code:
public void showImage(JLabel imageArea, String image){
BufferedImage img = null;
try {
img = (BufferedImage)ImageIO.read(new File(image));
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
any help is very much appreciated, and my sincere apologies if this is a noob question, I am quite new to java.
In the catch, you could load the standard image and show it
Basically check for image existence assuming path is valid otherwise get the standard image. You can have something similar:
public void showImage(JLabel imageArea, String image)
{
BufferedImage img = null;
try
{
file = new File(image);
if (file.exists())
{
img = ImageIO.read(file);
}
else
{
file = new File(standardImagePath);
img = ImageIO.read(file);
}
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}

Take a screenshot - Background Service

I'm trying to take a screenshot using a background service. This service is like a Facebook chathead, but I want it to take an screenshot when I do a click.
I've developed some code but it doesn't work. The last I've tried was:
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/capture/" + now + ".jpg";
// create bitmap screen capture
Bitmap bitmap;
View v1 = chatHead.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
File imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But is taking an screenshot to my button not to the screen.
I know the problem is here:
View v1 = chatHead.getRootView();
But I don't know how to fix it. Can anyone help me?
I'm actually using Android Studio 2.2.2 and Android 4.0 or greater.
For Lollipop and above you can use the MediaProjection API of Google to take the screenshot but you need to ask for the permission from the user.
You can find the sample screen capture code using MediaProjection Here
For the devices less then Lollipop you need root permission for it.
To get a screenshot containing views not belonging to your app you'll need to use the MediaProjectionManager.
See How to take a screen shot with status bar contents in android application?
Use MediaProjectionManager#createScreenCaptureIntent given in the MediaProjection API of Android. What you are doing now is taking the chatHead's root view's information rather than information present on the complete screen of your device including the status bar at the top.

Android - Copy image to clipboard, anyone got this working?

I am trying to copy a image file from my apk to the clipboard.
Here is how I am approaching it (roughly, i'm using a content provider locally which is out of the scope of the question.
ClipboardManager mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
values.put(MediaStore.Images.Media.DATA, filename.getAbsolutePath());
ContentResolver theContent = getContentResolver();
Uri imageUri = theContent.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);
mClipboard.setPrimaryClip(theClip);
With this code two things can happen:
1) java.lang.IllegalStateException: Unable to create new file
2) When pasting it only pastes the URI itself, not the image (even in compatible apps)
I don't see any example of anyone getting image pasting on android working, and I have searched for an answer extensively, both on google and stack overflow.
Can anyone help with this?
I would really appreciate someones assistance here.
PS: If it's just not possible to do I would also like to know that, to save wasting anymore time on this.
Thanks!
I have an option. Use the app SwiftKey as your keyboard on Android (it worked on Android 10). It allow you to access your photos library, so you will need to 1) download the image 2) open whatever app you are using and want to paste the image 3) using your SwiftKey keyboard, click on the "+" signal and then on the "pin" symbol (should be in the first line). 4) Finally, click on "create new" and it will access your photos to insert IN-LINE ANYWHERE.
I know that's not the best solution while on iOS you can just tap copy and paste. But it was the only solution that worked for me. Try for yourself. I hope that helps :)
There is no indication that such functionality is supported in Android.
The behavior is correct and the uri is the copied data not the bitmap.
It depends on whether the place you are pasting in can handle this uri.
The issue to the OP is this
values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
This is an invalid mime type. It should be
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
you can not copy that to clipboard because its impossible;
but you can do that by copying that to sdcard and then access that from every where that you want;
here is some code that helped me a lot and can help you too:
Context Context = getApplicationContext();
String DestinationFile = "the place that you want copy image there like sdcard/...";
if (!new File(DestinationFile).exists()) {
try {
CopyFromAssetsToStorage(Context, "the pictures name in assets folder of your project", DestinationFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
CopyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}

Save picture while Camera is in stopPreview mode

BACKGROUND
Hey so I have a camera that I have implemented myself in code. This means I access and control the camera hardware and use it to save pictures. I can save the picture using the Camera.takePicture() function when the camera is running: running means Camera.startPreview();
PROBLEM
My problem is that I want to be able to save the image also when the camera image is frozen: frozen is when Camera.stopPreview(); is called.When frozen I can see the image in my layout but how do I access it? Where is the image saved so that I might be able to modify it later?
Thanks in advance!
------------------Update 1
jpeg bla;
public class jpeg implements PictureCallback{
public void onPictureTaken(byte[] data, Camera camera) {
g_data = data;
}
}
This is part of my code. Here I am trying to write the data that would originally be saved to a global variable. However the value of g_data remains null and I am unable to set a breakpoint inside the onPictureTaken() call back function.
------------------Update 2
FileOutputStream outStream = null;
try {
// generate the folder
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MirrorMirror");
if( !imagesFolder.exists() ) {
imagesFolder.mkdirs();
}
// generate new image name
SimpleDateFormat formatter = new SimpleDateFormat("HH_mm_ss");
Date now = new Date();
String fileName = "image_" + formatter.format(now) + ".jpg";
// create outstream and write data
File image = new File(imagesFolder, fileName);
outStream = new FileOutputStream(image);
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) { // <10>
//Toast.makeText(ctx, "Exception #2", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {}
I used this code previously to save the file from the camera onPictureTaken() function. The key here is the byte[] data which I need to save and save later. However like I said I just get a null when I check it in the debugger.
Camera.takePicture never looks at the view you specified as previewDisplay. Actually, it isn't an ImageView, but a SurfaceView, and there are no API to read pixels from it.
You can call takePicture() preemptively just before you stopPreview(). Later, if you find out that you don't need the picture, just discard it.
Ok so the exact way to do this is to take the picture just before stopPreview() and save it to a temporary file. Actually with this implementation you never call stopPreview()(otherwise it will crash) since the takePicture() function stops the preview automatically.
try {
File temp = File.createTempFile("temp", ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
Now that we have the temporary file saved we will access it later and move it to our new desired file location.
How to copy file.
temp.deleteOnExit();
be sure to call deleteonExit() so that Android deletes the file after the app is closed(if so desired).

Categories

Resources