How to capture Images without transparent or black background? - java

I have a screen capture method that does half the job, it takes the screen shot but the images with PNG extention have transparent background and with JPEG it displays Black bakground. How can I capture the background (desktop wallpaper) ?
public void takeScreenshot() throws IOException {
date = new DateIAinnot();
view = ((Activity) context).getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/Pictures");
myDir.mkdirs();
fname = date.getDate(2) + ".png";
fname = fname.replace(':', '_');
fname = fname.replace(' ', '-');
file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
openScreenshot(file);
} catch (Exception e) {
e.printStackTrace();
}
}

Related

How do I make a notification of a downloaded pdf file?

I need to make notification on screen after pdf file had dowloaded. File dowload? but I cannot do notification on screen.
public void createDocumentAboutRegistration(User user){
PdfDocument myPdfDocument = new PdfDocument();
PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);
Paint myPaint = new Paint();
String myString = user.toString();
int x = 10, y=25;
for (String line:myString.split("\n")){
myPage.getCanvas().drawText(line, x, y, myPaint);
y+=myPaint.descent()-myPaint.ascent();
}
myPdfDocument.finishPage(myPage);
String myFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
String nameFile = "coupon-" + user.lastName + ".pdf";
File myFile = new File(myFilePath, nameFile);
try {
myPdfDocument.writeTo(new FileOutputStream(myFile));
Toast.makeText(RegistrationActivity.this, "Coupon generated and saved in your downloads.", Toast.LENGTH_LONG).show();
}
catch (Exception e){
e.printStackTrace();
Toast.makeText(RegistrationActivity.this, "Error", Toast.LENGTH_LONG).show();
}
myPdfDocument.close();
}

How I will display latest image to ImageView Another Activity?

My Application takes a picture from custom camera and save image to external storage.I save image by use code this.
SimpleDateFormat formatter = new SimpleDateFormat("dd_MM_yyyy_HH_mm", Locale.KOREA);
Date now = new Date();
String path = (Environment.getExternalStorageDirectory()+"/test"+".jpg");
String Newpath = (Environment.getExternalStorageDirectory()+"/"+"test_"+formatter.format(now)+".jpg");
Bitmap photo = BitmapFactory.decodeFile(path);
photo = Bitmap.createScaledBitmap(photo,480,640,false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 70,bytes);
File f = new File(Newpath);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
File file = new File(path);
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
example result > "test_13_12_2019_15_24" , "test_13_12_2019_15_26" , "test_13_12_2019_15_28"
It's time to now in external storage after take a picture but I want it show "test_13_12_2019_15_28" (latest picture) to imageView in another activity.
You can read your file like this.
public StringBuilder fromInternal(String filename) {
StringBuilder sb = new StringBuilder();
try {
FileInputStream fileInputStream = context.openFileInput(filename);
InputStreamReader inputStreamReader = new
InputStreamReader(fileInputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}

How to save the graph of JFreeChart in the PNG image?

There was a problem with saving the graphics I received in the form of a picture in a folder on the computer. It seems to me that the problem is in the saving method in the picture, but I do not know how to fix the problem. I marked the problem area in the code (saveImage), I hope for your help)
//create Graph
XYSeriesCollection seriesCollection1 = new XYSeriesCollection(series1);
chart1 = ChartFactory.createXYLineChart("Зависимость скорости полета от t",
"Время, с", "Скорость полета, км/ч", seriesCollection1, PlotOrientation.VERTICAL, false, true, false);
chartPanel1 = new ChartPanel(chart1);
chartPanel1.setPreferredSize(new Dimension(1300, 480));
panel.add(chartPanel1);
//saving method in picture
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
print(img.getGraphics()); // I think problem here.
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Ошибка сохранения", "", JOptionPane.ERROR_MESSAGE);
}
}
//listener
saveImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == saveImage) {
JFileChooser fc = new JFileChooser();
int op = fc.showSaveDialog(OpenFIle.this);
if (op == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4){
ext = filename.substring(len - 4, len);
}
if (ext.equals(".png")){
file = path + "\\" + filename;
}else {
file = path + "\\" + filename + ".png";
}
saveImage(new File(file));
}
}
}
});
}
The problem was solved in this way
public void saveImage(File file) {
Rectangle rec = chartPanel1.getBounds();
BufferedImage img = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
chartPanel1.paint(g);
try {
ImageIO.write(img, "png", file);
JOptionPane.showMessageDialog(null, "Данное изображение сохранено", "", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
}
}

Images corrupt on local storage after bringing them in from a URL

So I have it that when an in-app item is purchased the image they purchased is downloaded onto the phone. Works fine on external storage but I want it on INTERNAL storage. I'm using Picasso to load it into a bitmap then put into a PNG file. I'm not sure why it's getting corrupted along the way on internal storage. When the SD card is perfectly fine.
Anyone have any ideas why this is happening? Thanks!
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
//Internal storage
String path = getFilesDir().getAbsolutePath();
File imageFile = new File(path, "image.png");
FileOutputStream fos = null;
//TO SD Storage
File file = new File(
Environment.getExternalStorageDirectory().getPath());
File fileName = new File(file, "scrone.png");
if (isSDPresent) {
if (!fileName.getName().equals("scrone.png")) {
try {
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileName.getName().equals("scrone.png")) {
try {
fileName = new File(file, "scrtwo.png");
FileOutputStream ostream = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//I'm sorry for the mess you're about to witness
else if(!imageFile.exists()){
try {
Log.d(TAG, "File doesn't exist");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
else if(imageFile.exists())
{
try
{
Log.d(TAG, "File does exist");
imageFile = new File("image2.png");
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}).start();
}

Java save mp3 file

I am trying to create import images and mp3 files from one directory using a file chooser and save them to another . The images went fine but I cant seem to find out how to save the mp3 file .
Images
#Override
public void saveFile(File file) {
//Get image path
String imagePath = file.getAbsolutePath();
String imageName = file.getName();
System.out.println(imagePath);
//Read image
try {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage = ImageIO.read(new File(imagePath));
System.out.println("Reading complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
//write image
try {
f = new File("H:\\TestFolder\\images\\" + imageName); //output file path
ImageIO.write(bufferedImage, "jpg", f);
System.out.println("Writing complete.");
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
Mp3
#Override
public void saveFile(File file) {
try{
f = new File(file, "H:\\TestFolder\\test.mp3"); //file.getAbsolutePath();
}catch (Exception e) {
e.printStackTrace();
}
}
Use Files.copy(source, target, REPLACE_EXISTING);
https://docs.oracle.com/javase/tutorial/essential/io/copy.html
Try it like this:
File f = new File("H:\\TestFolder\\test.mp3");
InputStream is = new FileInputStream(f);
OutputStream outstream = new FileOutputStream(new File("H:\\TestFolder2\\blabla.mp3"));
byte[] buffer = new byte[4096];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();

Categories