Comments (7)
No , I am wrong. You are right. Issue was on my side. Now, it is fixed using below function.
` private fun convertJpgToPng(sourceuri: Uri): Uri {
val bitmap = MediaStore.Images.Media.getBitmap(context?.getContentResolver(), sourceuri);
//folder and file creation
val folderpath = context?.getFilesDir().toString() + File.separator + "sparklab"
val folder = File(folderpath)
val destinationFilename =
File(folderpath + File.separator + "sparklab_" + "hssn_mirza" + ".png")
try {
// Make sure the directory exists.
folder.mkdirs()
destinationFilename.createNewFile()
} catch (e: java.lang.Exception) {
Log.d("hssn---10", e.toString())
}
val outputStream = FileOutputStream(destinationFilename)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
outputStream.close()
return Uri.fromFile(destinationFilename)
}`
Thanks you so much.
from openai-kotlin.
Logs in organised way.
D loaded /vendor/lib64/egl/libGLES_mali.so D maxBitmapSize: 3243 D Uri scheme: file D Image size: [393:524] I Should crop: true D 1-->file:///storage/emulated/0/DCIM/Camera/IMG_20230125_180236381.jpg D 2-->file:///data/user/0/com.sparklab.ai/files/sparklab/sparklab_hssnmirza.png D endAllActiveAnimators on 0xb4000076461a44d0 (RippleDrawable) with handle 0xb400007556108220 I HttpClient: REQUEST: https://api.openai.com/v1/images/variations I METHOD: HttpMethod(value=POST) I COMMON HEADERS I -> Accept: application/json I -> Accept-Charset: UTF-8 I -> Authorization: Bearer <apiKey> I CONTENT HEADERS I -> Content-Type: multipart/form-data; boundary=-651c0b63-3b3247d1-5ce2608bf515725-441b30e6-4507d4a361a52508-1fc4734e- D tagSocket(96) with statsTag=0xffffffff, statsUid=-1 I HttpClient: RESPONSE: 400 BAD REQUEST I METHOD: HttpMethod(value=POST) I FROM: https://api.openai.com/v1/images/variations I COMMON HEADERS I -> access-control-allow-origin: * I -> connection: keep-alive I -> content-length: 161 I -> content-type: application/json I -> date: Wed, 25 Jan 2023 13:02:40 GMT I -> openai-organization: user-zinuwdnhn5tnrbfqaxqlrm8u I -> openai-processing-ms: 147 I -> openai-version: 2020-10-01 I -> strict-transport-security: max-age=15724800; includeSubDomains I -> x-android-received-millis: 1674651762739 I -> x-android-response-source: NETWORK 400 I -> x-android-selected-protocol: http/1.1 I -> x-android-sent-millis: 1674651761388 --------- beginning of crash I -> x-request-id: 8ba8f7abb134b74cd3ae5b2d6f41c489 E FATAL EXCEPTION: DefaultDispatcher-worker-8 Process: com.sparklab.ai, PID: 8356 com.aallam.openai.api.exception.OpenAIHttpException at com.aallam.openai.client.internal.http.HttpTransport.perform(HttpTransport.kt:24) at com.aallam.openai.client.internal.http.HttpTransport$perform$1.invokeSuspend(Unknown Source:15) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42) at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95) at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677) at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664) Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@9c8cf2c, Dispatchers.Default] Caused by: com.aallam.openai.api.exception.OpenAIAPIException: (statusCode=400, body='{ "error": { "code": null, "message": "Uploaded image must be a PNG and less than 4 MB.", "param": null, "type": "invalid_request_error" } } ') at com.aallam.openai.client.internal.http.HttpTransport.bodyOrThrow(HttpTransport.kt:32) at com.aallam.openai.client.internal.http.HttpTransport.perform(HttpTransport.kt:22) ... 9 more I Sending signal. PID: 8356 SIG: 9
from openai-kotlin.
Hi @hassanmirza444, I think you are trying to upload a jpg
image, while the API only accepts png
:
- The error from openai API is:
Uploaded image must be a PNG and less than 4 MB
. - The image you are trying to upload is:
IMG_20230125_180236381.jpg
PS: I've deleted your API key from the stacktraces above (and edit history)
from openai-kotlin.
Yes brother, What I am doing is I select a file from gallery, and Logged it as 1.
1-->file:///storage/emulated/0/DCIM/Camera/IMG_20230125_180236381.jpg
Then I had converted it in png. Also, I have show it in an imageView. its completely fine.
2-->file:///data/user/0/com.sparklab.ai/files/sparklab/sparklab_hssnmirza.png
from openai-kotlin.
Can you share how did you convert it from jpg
to png
please ?
from openai-kotlin.
@aallam Here is code, on Image selected from gallery and conversion to png
` override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
//Image Uri will not be null for RESULT_OK
Log.d("hssn", "1-->" + data?.data!!.toString())
seletedPngFileUri = convertJpgUriToPngUri(data.data!!, "hssnmirza")!!
Log.d("hssn", "2-->" + seletedPngFileUri.toString())
binding.ivInput.setImageURI(seletedPngFileUri)
} else if (resultCode == ImagePicker.RESULT_ERROR) {
Toast.makeText(requireContext(), ImagePicker.getError(data), Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(requireContext(), "Task Cancelled", Toast.LENGTH_SHORT).show()
}
}
private fun convertJpgUriToPngUri(sourceuri: Uri, fName: String): Uri? {
val sourceFilename = sourceuri.path
val folderpath = context?.getFilesDir().toString() + File.separator + "sparklab"
val folder = File(folderpath)
var destinationFilename = File(folderpath + File.separator + "sparklab_" + fName + ".png")
try {
// Make sure the Pictures directory exists.
folder.mkdirs()
destinationFilename.createNewFile()
} catch (e: java.lang.Exception) {
Log.d("hssn---0", e.toString())
}
var bis: BufferedInputStream? = null
var bos: BufferedOutputStream? = null
try {
bis = BufferedInputStream(FileInputStream(sourceFilename))
bos = BufferedOutputStream(FileOutputStream(destinationFilename, false))
val buf = ByteArray(1024)
bis.read(buf)
do {
bos.write(buf)
} while (bis.read(buf) != -1)
} catch (e: IOException) {
e.printStackTrace()
Log.d("hssn", e.toString())
// destinationFilename = null
} finally {
try {
bis?.close()
bos?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return Uri.fromFile(destinationFilename)
}
`
from openai-kotlin.
Correct me if I am wrong, in this code snippet you make a copy of the file with different extension, not actually converting it, right ?
from openai-kotlin.
Related Issues (20)
- Bug with integration openai-kotlin library HOT 1
- Unable to integrate the library in a Kotlin springboot project HOT 1
- Illegal input: Fields [createdAt, messageId] are required for type with serial name 'com.aallam.openai.api.message.MessageFile', but they were missing at path: $[Brief Issue Description]
- Chose quality for image generation
- Feature Request: Add Support for Content Filter Response Deserialization OR Expose Raw Response in OpenAI Kotlin Client
- Is it possible to add a header for each request?
- Upload file to an asstistant does not work due to invalid url
- Missing systemFingerprint field in ChatCompletionChunk
- Wrong serialization of tools / function description field when using chat completion function calling HOT 1
- Feature Request: A collection of well-known ModelId values
- ChatGLM:Illegal input: Fields [code, param] HOT 1
- Getting messages from assistant thread throws MissingFieldException when there's image content
- Field 'param' is required for type with serial name 'com.aallam.openai.api.exception.OpenAIErrorDetails'
- Question: GPT4-vision HOT 4
- Anthropic Claude? HOT 2
- JsonConvertException when trying to Output Images: Missing 'file_id' Field, Sample Code for Showing Assistants Image Content? HOT 1
- Build Issue: add package name to Quality.kt
- Feature request: assistant streaming
- Invalid value: 'image'. Supported values are: 'text' and 'image_url'
- [Public accessible docs for GPT Vision model]
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from openai-kotlin.