From getExternalStorageDirectory to internal storage - java

again I need a little help from you. I have this code for simple photo app, but this code save edited image on SD card, but I want change this to save image on internal memory of phone.
private File captureImage() {
// TODO Auto-generated method stub
OutputStream output;
Calendar cal = Calendar.getInstance();
Bitmap bitmap = Bitmap.createBitmap(ll1.getWidth(), ll1.getHeight(),
Config.ARGB_8888);
/*
* bitmap = ThumbnailUtils.extractThumbnail(bitmap, ll1.getWidth(),
* ll1.getHeight());
*/
Canvas b = new Canvas(bitmap);
ll1.draw(b);
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath() + "/background_eraser/");
dir.mkdirs();
mImagename = "image" + cal.getTimeInMillis() + ".png";
// Create a name for the saved image
file = new File(dir, mImagename);
// Show a toast message on successful save
Toast.makeText(SelectedImgActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
Any suggestions how to do this? I think I must change only Environment.getExternalStorageDirectory to something other, but what?
Thank you!
Edited:
I was change this line to File filepath = Environment.getDataDirectory(); and I think this works. But this make new folder in root folder...I want it in pictures... How to archive this?
Edited 2:
Now I was edited code to this
private File captureImage() {
// TODO Auto-generated method stub
OutputStream output;
Calendar cal = Calendar.getInstance();
Bitmap bitmap = Bitmap.createBitmap(ll1.getWidth(), ll1.getHeight(),
Config.ARGB_8888);
/*
* bitmap = ThumbnailUtils.extractThumbnail(bitmap, ll1.getWidth(),
* ll1.getHeight());
*/
Canvas b = new Canvas(bitmap);
ll1.draw(b);
// Find the SD Card path
File filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// File filepath = Environment.getDataDirectory(Environment.DIRECTORY_PICTURES);
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath() + "/Background Remover/");
dir.mkdirs();
mImagename = "image" + cal.getTimeInMillis() + ".png";
// Create a name for the saved image
file = new File(dir, mImagename);
// Show a toast message on successful save
Toast.makeText(SelectedImgActivity.this, "Image Saved",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
Everything works fine, except Toast show...

Replace:
File dir = new File(filepath.getAbsolutePath() + "/background_eraser/");
With:
File dir = context.getFilesDir().getAbsolutePath() + File.separator + "background_eraser";
You can use:
FileInputStream fis = context.openFileInput(name);
Added in API level 1
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Related

Multiple images to pdf. How do i string multiple images so bitmapfactory can decode

My user inputs a folder name. Then takes pictures which are saved in the folder. I want to take all the files in the folder which will all be jpg files and create one pdf. There wouldnt be more than 5 images in the folder.
How do i extract all of the files out of the folder so i can pass the strings to the bitmapfacory.decodeFile
So far i have tried the following code.
To test the pdfcreater i named the jpg something in the code. Then took a pic and renamed it the same. It created the pdf with my image.
I have also tried the currentPhotoPath and that works for the one current photo.
The folder that holds all the JPG's is folderName1
private void buttonCreatePDF() {
Intent folInt = getIntent();
String folderName1 = folInt.getStringExtra("Value");
String file1 = directoryPDF + folderName1 ;
Bitmap bitmap = BitmapFactory.decodeFile(file1);
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
page.getCanvas().drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
String pdfFile = directoryPDF + "/" + folderName1 + ".pdf";
File myPDFfile = new File(pdfFile);
try {
pdfDocument.writeTo(new FileOutputStream(myPDFfile));
Toast.makeText(this, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}
}

android: how to get a screenshot for the whole screen programmtically

here is a code to take a screenshot .. but the problem is it takes a screenshot for the application only .. not the whole screen (back and home button and notification bar )
is there any way that I can take a screenshot for the whole screen not only the application
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 DOM
e.printStackTrace();
}
}

FileNotFoundException when reading a BufferedImage

I'm trying to crop an image received from a form upload. Before I crop it I save it, then I retrieve it again as a BufferedImage (because I don't know how to turn a part into a buffered Image). I then crop this image, but when I try to save it again I get a java.io.FileNotFoundException (access denied)
The first image gets saved correctly, I get the exception when I try to pull it back.
Is it possible to turn my part into a buffered image and then save it? Instead of doing double work. or else is there some fix to my below code.
String savePath = "path";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
//functionality to ormit non images
String fileName = extractFileName(part);
part.write(savePath + "/" + fileName);
String imagePath = savePath + "/" + fileName;
BufferedImage img = null;
try {
img = ImageIO.read(new File(imagePath));
img = img.getSubimage(0, 0, 55, 55);
ImageIO.write(img, "jpg", fileSaveDir);
} catch (IOException e) {
System.out.println(e);
}
}
ImageIO.write((RenderedImage im, String formatName, File output));
Parameters:
im a RenderedImage to be written.
formatName a String containg the informal name of the format.
output a File to be written to.
As per documentation output file parameter is the file object where it would be image written where you have passed the parent directory file object.

How to add watermark on video using mp4parser in android?

I had successfully convert recorded video into "out.h264" format and also audio into ".AAC" format using mp4parser. Now I want to implement "watermark image" on my recorded video. Is this possible with mp4parser to add watermark on video? I have checked GPUimages too. But there is no way to add effect on video, Its' example shows effect for only Images. So my question is How can I add watermark on video?
Below is my code for audio video :
File sdCard = Environment.getExternalStorageDirectory();
IsoFile isoFile = new IsoFile(videosPath);
TrackBox trackBox = (TrackBox) Path.getPath(isoFile, "/moov/trak/mdia/minf/stbl/stsd/avc1/../../../../../");
SampleList sl = new SampleList(trackBox);
File out = new File(sdCard + "/out.h264");
if (out.exists()) {
out.delete();
}
FileChannel fc = new RandomAccessFile(out, "rw").getChannel();
ByteBuffer separator = ByteBuffer.wrap(new byte[] { 0, 0, 0, 1 });
fc.write((ByteBuffer) separator.rewind());
// Write SPS
fc.write(ByteBuffer.wrap(((AvcConfigurationBox) Path.getPath(trackBox, "mdia/minf/stbl/stsd/avc1/avcC")).getSequenceParameterSets().get(0)));
// Warning:
// There might be more than one SPS (I've never seen that but it is possible)
fc.write((ByteBuffer) separator.rewind());
// Write PPS
fc.write(ByteBuffer.wrap(((AvcConfigurationBox) Path.getPath(trackBox, "mdia/minf/stbl/stsd/avc1/avcC")).getPictureParameterSets().get(0)));
// Warning:
// There might be more than one PPS (I've never seen that but it is possible)
int lengthSize = ((AvcConfigurationBox) Path.getPath(trackBox, "mdia/minf/stbl/stsd/avc1/avcC")).getLengthSizeMinusOne() + 1;
for (Sample sample : sl) {
ByteBuffer bb = sample.asByteBuffer();
while (bb.remaining() > 0) {
int length = (int) IsoTypeReaderVariable.read(bb, lengthSize);
fc.write((ByteBuffer) separator.rewind());
fc.write((ByteBuffer) bb.slice().limit(length));
bb.position(bb.position() + length);
}
}
fc.close();
Log.e(TAG, "Converted Path: " + out.getAbsolutePath() + " Start Time Convert: " + new Date());
H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl(out.getAbsoluteFile()));
AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl(audioPath));
CroppedTrack aacTrackShort = new CroppedTrack(aacTrack, 1, aacTrack.getSamples().size());
// MP3TrackImpl accTrackImpl = new MP3TrackImpl(new FileDataSourceImpl(audioPath));
Movie movie = new Movie();
movie.addTrack(h264Track);
movie.addTrack(aacTrackShort);
Container mp4file = new DefaultMp4Builder().build(movie);
File output = new File(sdCard + "/output_KanAK.mp4");
if (output.exists()) {
output.delete();
}
#SuppressWarnings("resource")
FileChannel fc1 = new RandomAccessFile(output, "rw").getChannel();
mp4file.writeContainer(fc1);
fc1.close();
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.velfee);
gpuImage.saveToPictures(largeIcon, output, 100, new OnPictureSavedListener() {
#Override
public void onPictureSaved(Uri uri) {
// TODO Auto-generated method stub
Log.e(TAG, "Picture save Uri");
GPUImageDifferenceBlendFilter filter;
filter.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
}
});
Any help would be appreciated!! Thanks in advance.
You can use a String as a watermark using the subtitle example in the github page. Set the limits to your own but ofcourse you wont be able to use image.

how to save the the image in folder on disk using java

I want to save the image on disk such as c:/images which is captured by webcam using java ..and again I want to display that image on JForm as a label...
is this possible using java and netbeans
I'm new in java
you can save image
private static void save(String fileName, String ext) {
File file = new File(fileName + "." + ext);
  BufferedImage image = toBufferedImage(file);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
and read image from disk and show into label as
File file = new File("image.gif");
image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
You can use BufferedImage to load an image from your hard disk :
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}
Try this link for further information. Reading/Loading Images in Java
And this one for saving the image. Writing/Saving an Image
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
Pure Java, not third party library needed:
byte[] image = /*your image*/
String filePath = /*destination file path*/
File file = new File(filePath);
try (FileOutputStream fosFor = new FileOutputStream(file)) {
fosFor.write(image);
}
//Start Photo Upload with No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with No//

Categories