gpt4 book ai didi

java - 我可以以 mode_private 保存图像吗?

转载 作者:行者123 更新时间:2023-12-01 07:33:19 25 4
gpt4 key购买 nike

目前,我使用以下方法在 mode_private 中保存 XML 文件:

public void Save_Data(String filename, String Datastring, Context context) {
FileOutputStream fos;

try {
fos = context.openFileOutput(filename, context.MODE_PRIVATE);
fos.write(Datastring.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

我想将 URL 中大约 5kb 的小图像保存到我的应用程序空间中的 mode_private 中。是否可以以 mode_private 保存图像?如果是这样,谁能告诉我如何修改下面的方法来做到这一点?

public void DownloadFromUrl(final String DownloadUrl, final String fileName) {


Thread web = new Thread(){
public void run(){


try {
File root = Environment.getExternalStorageDirectory();

File dir = new File (root.getAbsolutePath() + "/Chats");
if(dir.exists()==false) {
dir.mkdirs();
}

URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);

long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);

/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();

/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);

/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}


/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}

}
};
web.start();
}

最佳答案

所以我终于想出了如何在 mode_private 中保存图像

下面的方法采用 Bitmap 并将其保存到您的应用程序私有(private)空间的 mode_private 中。

 public String writeFileToInternalStorage(Bitmap outputImage){
String fileName = fileName + ".png";

FileOutputStream fos = null;
try {
fos = openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputImage.compress(Bitmap.CompressFormat.PNG, 90, fos);

return fileName;
}

这将从应用程序私有(private)空间读取图像并将其转换为位图:

 Bitmap bitmap = BitmapFactory.decodeFile(this.getApplicationContext().getFilesDir() + "/"+fileName);

希望这对某人有帮助。

关于java - 我可以以 mode_private 保存图像吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com