So I use this function to save a bitmap to gallery, but I'm beginner and it's not work.
public static String saveBitmapToGallery(Context context, Bitmap bitmap, String title, String desc){
return MediaStore.Images.Media.insertImage(context.getContentResolver(),bitmap, title, desc);
}
It's called in an AsyncTask class. I save the return value to "saveUrl" String. (I checked and it's not null.)
And in the onPostExecute I call this function (if the "saveUrl" is'n null) to refresh gallery:
MediaScannerConnection.scanFile(actualMainView.getContext(), new String[]{saveUrl}, null, null);
The problem is that the file is not created properly. Size is 0B, title and creation date are incorrect. And the thumbnail is displayed correctly in the file manager.
What is missing to make it work? Thank you in advance for your help!
Try this one, maybe it helps you.
private void saveImage(Bitmap bitmatFile, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmatFile.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I wrote the code below to save the image source.
here is my code
public void SavePictureToDisk(string filename, byte[] imageData)
{
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
Context context = MainActivity.Instance;
var pictures = storagePath.AbsolutePath;
string name = filename + System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filePath = System.IO.Path.Combine(pictures, name);
try
{
Logger.Instance.Write($"{name}");
System.IO.File.WriteAllBytes(filePath, imageData);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new File(filePath)));
context.SendBroadcast(mediaScanIntent);
}
catch (System.Exception e)
{
Logger.Instance.Write(e.ToString());
}
}
}
On emulator and on my gelaxy s 21, the save works fine. However, in previous models of gelaxy s 21, there was a bug that could not be saved. May I know what I did wrong?
It wasn't an issue with permission settings.
I get "System can't find the path specified." when I try to upload an image to project folder inside resources.
Here is my project structure:
|Project
|src
|main
|resources
|META-INF.resources
|images
Project Structural Hierarchy can be seen here in the image format.
I have defined the path as
String path = "\\resources\\images\\" + imageName; File file = new File(path );
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(path );
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
What can be the exact path to images folder under META-INF.resources directory?
The following should work fine:
//App.java
String path = "\\META-INF.resources\\images\\" + imageName;
InputStream is = App.class.getClassLoader().getResourceAsStream(
path);
In a nut shell, use "getClassLoader().getResourceAsStream()" instead of FileInputStream or FileOutputStream.
Following worked for me.
In application.properties I defined my path string as:
image.path = src/main/resources/META-INF/resources/images/uploads/
Here is my uploadImage function in a class file.
#Autowired
private Environment environment;
public String uploadImg(FileUploadEvent event, String imagePrefix) {
String path = environment.getProperty("image.path");
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
String name = fmt.format(new Date())
+ event.getFile().getFileName().substring(
event.getFile().getFileName().lastIndexOf('.'));
name = String.format("%s%s" ,imagePrefix ,name );
String finalPath = String.format("%s%s" ,path ,name);
System.out.println("image is going to save # " +finalPath);
File file = new File(finalPath).getAbsoluteFile();
try {
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
} catch (Exception e) {
System.out.println(e);
}
return name;
}
I am not sure whether it will work at production or not. Basically I get absolute path of the project and then append my relatively extracted path. Correct me if I am wrong.
I am having problems getting an image back from the default android gallery. All I want to do is call the Android standard gallery intent and return the uri for the image in my onActivityResult. When I run this code it open the gallery just fine but then it force closes whenever I click on a picture. Any tips for this would be helpful.
private void doGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setType(IJudgeSingleton.IMAGEINTENT);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), IJudgeSingleton.REQUEST_CODE_GALLERY);
}
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;
Figured it out my file was pointing to a null so that's what was giving me the force close. Also I had to add change some code around in my onActivityResult for REQUEST_CODE_GALLERY. I have posted the added code below for anyone who has this problem.
case IJudgeSingleton.REQUEST_CODE_GALLERY:
Uri uri = data.getData();
//This takes the uri/image returned from the gallery intent a places it into a file.
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(mSingleton.mFileTemp); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
in.close();
out.close();
} catch (Exception ex) {
Log.e(this.getClass().getName(),"REQUEST_CODE_GALLERY");
}
// mSingleton.mFileTemp = new File(getMediaPath(uri));
try {
IJudgeSingleton.copy(mSingleton.mFileTemp, mSingleton.mCropFileTemp);
mData.setImageSet(true, mSingleton.mFileTemp.toURI().toString(), true);
mData.setPhoto(true);
}
catch (IOException e) {
Log.d(this.getClass().getName(), "REQUEST_CODE_GALLERY", e);
}
break;
case IJudgeSingleton.REQUEST_CODE_DEFAULT_CAPTURE:
mData = data.getParcelableExtra(IJudgeSingleton.SURVEY_INTENT);
showListView();
completedIntent = false;
I have researched and tried to refer back to my fileChooser.getSeletedFile() in my save as action but can not work out how to check whether or not a file has been created. Here is my attempted code so far:
Save as code(works well):
public void Save_As() {
fileChooserTest.setApproveButtonText("Save");
int actionDialog = fileChooserTest.showOpenDialog(this);
File fileName = new File(fileChooserTest.getSelectedFile() + ".txt");
try {
if (fileName == null) {
return;
}
BufferedWriter outFile = new BufferedWriter(new FileWriter(fileName));
outFile.write(this.jTextArea2.getText());//put in textfile
outFile.flush(); // redundant, done by close()
outFile.close();
} catch (IOException ex) {
}
}
"Save" code doesn't work:
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
File f = fileChooserTest.getSelectedFile();
try {
if (f.exists()) {
BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
String text = ((JTextArea) jTabbedPane1.getSelectedComponent()).getText();
bw1.write(text);
bw1.close();
} else {
Save_As();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Instead of storing an instance to the JFileChooser rather store an instance to the File (wich will be null before any save has been performed). In your SaveActionPerformed method check if the file is null. If it is null then do a Save_As and store the selected file in your file variable, if it is not null then do a normal save into the file.
because use zk upload component to upload a image,then insert the context path of the image to the CKEditor is too complex,
and at http://ckeditor.com/demo, you can see that CKEditor can upload image and flash etc,
but in zk, the CKEditor don't have this feature,
is that mean CKEditor in zk can't upload file?
I'm afraid this is not possible with zk.
I wrote a workaround to do this. You have to add a button to your GUI and add this EventListener to the button:
private class onUpload implements EventListener
{
#Override
public void onEvent(Event event) throws Exception
{
Media media = ((UploadEvent) event).getMedia();
if (media.getContentType().contains("image"))
{
reader.upload(media.getStreamData(), media.getName());
String description = edDescription.getValue();
description += "<img alt=\"\" src=\"/" + media.getName() + "\" />";
edDescription.setValue(description);
}
else
{
new Messagebox().show(_T("You can only upload images!"), _T("Not an image!"), Messagebox.OK, Messagebox.ERROR);
}
}
}
Reader is my class which handles file transfers and is used to write the data to the docroot. In my case the docroot of glassfish 3.1 can be located with the following code. I wrote the method getDocFolder() for ist because it also adds subfolders for each user if they don't already exists.
File file = new File("../docroot/");
This is the code for the upload method of the reader:
InputStream inputStream = null;
try
{
inputStream = new ByteArrayInputStream(imageStream);
String filename = getDocFolder()+"/"+imageName;
File file = new File(filename);
OutputStream out=new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len = inputStream.read(buf)) > 0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (Exception ex)
{
Logger.getLogger(ImageReader.class.getName()).log(Level.SEVERE, "Error writing image", ex);
}
finally
{
try
{
inputStream.close();
}
catch (IOException ex) {}
}
I hope this helps