I need to export an image from a libGDX game, and make it appear in the default Photos app on an iPad.
Currently, I do it like this:
Pixmap image = getScreenshot();
FileHandle file;
String filename = "diplom_" + game.player.getID() + ".png";
if(Gdx.files.isExternalStorageAvailable())
file = Gdx.files.external(filename);
else
file = Gdx.files.local(filename);
PixmapIO.writePNG(file, image);
pixmap.dispose();
But the screenshot doesn't appear anywhere. How can I make it appear in the Photos app?
What I am doing in such case is:
private NSData getImageAsNsData(Pixmap pixmap) {
FileHandle file = Gdx.files.local("tmpImage.png");
PixmapIO.writePNG(file, pixmap);
NSData imageData = NSData.read(file.file());
file.delete();
return imageData;
}
public void sendToGallery(Pixmap pixmap) {
NSData imageData = getImageAsNsData(pixmap);
uiImage = new UIImage(imageData);
uiImage.saveToPhotosAlbum(new VoidBlock2<UIImage, NSError>() {
#Override
public void invoke(UIImage uiImage, NSError nsError) {
if (nsError!=null)
Gdx.app.log("Error", "Unable to save: " + nsError.getLocalizedDescription());
}
});
}
I hope it helps you. :)
At first try adding logger so you see where you add put the file.
if you put it in local:
Local files are stored relative to the application's root or working directory on desktops and relative to the internal (private) storage of the application on Android. Note that Local and internal are mostly the same on the desktop.
if external
External files paths are relative to the SD card root on Android and to the home directory of the current user on desktop systems.
refare to FileHandling libGDX wiki
So i guess you save it in local thats why you wont find it in iOS. Else you need to create the right path to the pictures folder. Else you just save it at the same folder where the apps get installed. But i think youll need to use the absolut verion of the filehandle. Else you can save something at an total different path.
In this case, “myfile.txt” needs to be in the users’ home directory (/home//myfile.txt on linux or \Users\\myfile.txt on Windows and MacOS) on desktop, and in the root of the SD card on Android.
FileHandle handle = Gdx.files.absolute("/some_dir/subdir/myfile.txt");
Related
so i know there are alot of questions about creating a text file in android but i cant find any answers to my specific questions.
So the device I'm using is not an phone or a tablet, its a controller with android on it so the file directory is getting me confused. i want to create a new file either on the sd card or the device itself (it doesn't really matter as long as i can see it). firstly, the device doesn't have google docs or sheets or anything like that, will i need to install one of these apps on it for it to be able to read .txt files? or does android have some sort of internal software to do that?
Secondly, i've found alot of code on how to create a new file but most of it seems to gloss over how to get file directory, is there a specific way i can get the file directory?
This is what im using so far and im not getting any errors but its also not creating any files (or at-least none that i can see).
public void WriteToText(){
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
1, I think all devices have Html viewer which can view the text files. If you click a text file in a file manager app, it should prompt you with a list of apps that can view the text file.
2, Your code is correct, but it creates a file in the app's private file directory, which is not visible to all other apps, including file manager apps. This is because of Android security policy to prevent any app to steal information from other apps.
If you want to write a file which is visible to other apps like file manager, there are 2 ways.
in old api level (<29?) you can get the get external storage with
Environment.getExternalStorageDirectory()
you will need to request permission for it.
save the file in your app's private directory like what you have done, then create a chooser to share it out with correct mime type (txt/plain?), it will prompt you to select app that can view this mime type like what file manager does.
Why is this so difficult to do in android? I know its easy for images, but why not .gifs?
I have this code here which saves it to an SD card, but I am trying to account for the user not having an SD card.
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "GIFName_" + System.currentTimeMillis() +".gif");
try {
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
} catch(Exception e) {
e.printStackTrace();
}
My app basically converts images to .GIFS, and right now it saves it on the sd card, but I want to save it to the gallery. Is there any way to do this easily? I know you can do it for images, but can you for .GIFS that are created?
What exactly do you mean by Gallery? There is no directory called Gallery. However there is an application called Gallery and I hope that's what you mean.
Environment.getExternalStorageDirectory() will return the root path to the external storage. This has no dependency to the file you are trying to save. If you want save to the Pictures directory, then you can do Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
Gallery is an application in android that scans the whole system and adds all media items to it. If you try saving a file, be it .gif or .jpg, or .png, programmatically in Android, there is no guarantee that the file will be picked up by Gallery immediately. That's why you need to use MediaScannerConnection. This will let you add your newly created file to be shown in Gallery.
Something like below:
MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null, null);
Documentation: https://developer.android.com/reference/android/media/MediaScannerConnection.html#scanFile(java.lang.String, java.lang.String)
I'm sorry for asking such a beginner question, but I just can't get it to work and I can't find the answer anywere either.
I want to have an image inside my .jar file and load it. While that sounds simple, I was only able to load an image while running from inside the IDE but not anymore after making the .jar (Thanks to google I was able to get the .png inside the .jar). Here is what I tried:
BorderPane bpMain = new BorderPane();
String fs = File.separator;
Image imgManikin;
try {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()+"\\manikin.png"));
} catch (URISyntaxException e) {
imgManikin = new Image(
Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
System.out.println(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png");
bpMain.setBottom(new Label(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"\\manikin.png"));
}
//Image imgManikin = new Image("file:src\\manikin.png");
ImageView imgvBackground = new ImageView(imgManikin);
imgvBackground.setFitWidth(100);
imgvBackground.setPreserveRatio(true);
bpMain.setCenter(imgvBackground);
primaryStage.setTitle("Kagami");
primaryStage.setScene(new Scene(bpMain, 300, 275));
primaryStage.show();
Needlessly to say it didn't work. It is showing me the Label at the bottom with the path just as intended, but it seams like the path just isn't right. (I also tried using the File.seperator instead of \\ and even /, but I got the same result every time: It showes me the path but won't load the image.
I'm using Windows 7, the IDE is IntelliJ and I have the newest Java update.
If the jar file is on the classpath of your application and the image to be loaded is located at the root of the jar file, the image can be loaded easily by:
URL url = getClass().getResource("/manikin.png");
BufferedImage awtImg = ImageIO.read(url);
Image fxImg = SwingFXUtils.toFxImage(awtImg, new Image());
Image fxImgDirect = new Image(url.openStream());
While ImageIO returns a BufferedImage this can be converted to a fx Image using the SwingUtils. However the preferred way is to directly create a new Image instance using the InputStream from the URL.
See also Load image from a file inside a project folder. If done right it does not matter if it is loaded from a jar file or the local file system.
The Image::new(String) constructor is looking for a URL. It is possible to construct a URL for a resource in a jar file, but it's much easier to use ClassLoader::getResource or ClassLoader::getResourceAsStream to manage that for you.
Given the file structure:
src/
SO37054168/
GetResourceTest.java
example/
foo.txt
The following, packaged as a jar will output
package SO37054168;
public class GetResourceTest {
public static void main(String[] args) {
System.out.println(GetResourceTest.class.getClassLoader().getResource("example/foo.txt"));
System.out.println(GetResourceTest.class.getClassLoader().getResourceAsStream("example/foo.txt"));
}
}
jar:file:/home/jeffrey/Test.jar!/example/foo.txt
sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#7f31245a
Note how the URL for the resource is not the same as the URL you were trying to construct. The protocol is different, and you need to have the ! after the path to the jar file.
Hi I want to make images invisible to android gallery or any third party gallery app, the image will be places in specific folder on SD card.
For example I have following code to save an image to a folder called myimages. I just want the images stored in myimages folder should not be visible to any gallery app and only my own application can access these images.
void saveBitmap(Bitmap bmp)
{
FileOutputStream os;
String dirName = "/mvc/mvc/myiamges/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
String root = Environment.getExternalStorageDirectory()
.toString();
File dir = new File (root + dirName);
boolean created=dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null),
// this.dirName+fileName);
//this function give null pointer exception so im
//using other one
File file = new File(dir, "aeg2.png");
os = new FileOutputStream(file);
}else{
os = openFileOutput("aeg2.png", MODE_PRIVATE);
}
bmp.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
Rename those files with custom extensions like filename.extension.customextension
like hello.avi.topsecret.
When you need the file to be ready mode to play rename it to proper extension, play and rename it back.
This should work for you.
or
Prefix your folder name with a dot "."
Check these links for more info:
http://www.makeuseof.com/tag/hide-private-picture-folders-gallery-android/
Yes, save it with any extension you want or even without extension.
In your app, just read it as normal image file.
Create an empty file inside your image store folder named '.nomedia' <- atention to the initial point.
All media files sabed inside this folder will not be showed in galery browsers.
I am developing web method for webservice in java. In this web method I have to read image from my images folder which resides in my webservice project folder. I am using the code as follows.
#WebMethod(operationName = "getAddvertisementImage")
public Vector getAddvertisementImage()
{
Image image = null;
Vector imageList = new Vector();
try
{
File file = new File("E:/SBTS/SBTSWebservice/web/adv_btm.jpg");
image = ImageIO.read(file);
imageList.add(image);
}
catch (IOException e)
{
e.printStackTrace();
}
return imageList;
}
I am unable to read image from images folder.I am getting error image file "input file can't read" at image = ImageIO.read(file); how to resolve this issue ? Is there any mistake in my code or is there any other way to read image ? if there is any mistake in my code then can you proide me the code or link through which i can resolve the above issue.
Is the E:\ drive mapped on your web server? The Java compiler has no idea that you might access files outside of its scope and how it could tell your web server to map a network drive or a local hard disk which is attached to your development computer.
The solution is to put the image file into the same directory as the Java source file and then use
InputStream in = getClass().getResourceAsStream("adv_btm.jpg");
Check that your IDE (or whatever you use to build your application) does copy the image file in the same directory where it creates the .class file. Then it should work.