Blackberry 10 image upload - image

I am getting this error when trying to upload image Process 1780056901 (Zain) terminated SIGSEGV code=1 fltno=11 ip=00000000. I am getting no help from blackberry forums, and most of blackberry documention is next to trash..and so many codes they have put are flat out wrong documentation and dont work.
void ApplicationUI::getPicture()
{
FilePicker* filePicker = new FilePicker();
filePicker->setType(FileType::Picture);
filePicker->setTitle("Select Picture");
filePicker->setMode(FilePickerMode::Picker);
filePicker->open();
QObject::connect(filePicker,
SIGNAL(fileSelected(const QStringList&)),
this,
SLOT(onFileSelected(const QStringList&)));
}
void ApplicationUI::onFileSelected(const QStringList& list) {
try
{
QFile file (list[0]);
ImageView* ay = root->findChild<ImageView*>("imageName");
if(ay != NULL)
ay->setImage(Image(list[0]));
QString body = "" ;
QSettings settings("Netvariant", "Zain");
QString locale_string = settings.value("lang").toString();
if(locale_string == "ar")
locale_string == "ar";
else
locale_string = "en";
const QUrl url("myurl");
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"imageFile\""));
imagePart.setRawHeader("Content-ID", "my#content.id"); // add any headers you like via setRawHeader()
file.open(QIODevice::ReadOnly);
imagePart.setBodyDevice(&file);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
file.setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(imagePart);
QNetworkRequest request(url);
QNetworkAccessManager* netManager = new QNetworkAccessManager(this);
QNetworkReply *reply = netManager->post(request, multiPart);
}
catch(...)
{
}
}

Related

VLCSharp Unity3D, video Streaming freezes but audio still working

I want to get a RTMP link and stream the video at my unity project but, and it works fine.... just 4 frames long cause after that it freezes, but audio stills playing.
For this code i´m using VSCode,Unity3D and the public example that the creators have on their github.
// This is the start, where i initialize things of course hahauhsuhs
void Start()
{
Core.Initialize(Application.dataPath);
_libVLC = new LibVLC();
PlayPause();
}
//Then here we have the method play and Pause, where we play Media Player and give him the media URL that works for a few frames.
private void PlayPause()
{
if (_mediaPlayer == null)
{
_mediaPlayer = new MediaPlayer(_libVLC);
}
if (_mediaPlayer.IsPlaying)
{
_mediaPlayer.Pause();
}
else
{
_isPlaying = true;
if (_mediaPlayer.Media == null)
{
// playing remote media
_mediaPlayer.Media = new Media(_libVLC, new Uri(URL));
}
_mediaPlayer.Play();
}
}
// This method will be execute every frame and do some crazy stuff that i can´t explane right now.
private void Update()
{
//A few checks before executing video
if (!_isPlaying) return;
if (URL.Equals(null)) URL = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"; //if URL is null give the BigChungus Bunny video
//Execute Video
if (_tex == null)
{
// If received size is not null, it and scale the texture
uint i_videoHeight = 0;
uint i_videoWidth = 0;
_mediaPlayer.Size(0, ref i_videoWidth, ref i_videoHeight);
var texptr = _mediaPlayer.GetTexture(out bool updated);
if (i_videoWidth != 0 && i_videoHeight != 0 && updated && texptr != IntPtr.Zero)
{
Debug.Log("Creating texture with height " + i_videoHeight + " and width " + i_videoWidth);
_tex = Texture2D.CreateExternalTexture((int)i_videoWidth,
(int)i_videoHeight,
TextureFormat.RGBA32,
false,
true,
texptr);
RenderSettings.skybox.mainTexture = _tex;
}
}
else if (_tex != null)
{
var texptr = _mediaPlayer.GetTexture(out bool updated);
if (updated)
{
_tex.UpdateExternalTexture(texptr);
}
}
}
this is my first real question on stackover flow so this post can have some issues, I´m open for suggestion to improve it.
I found that the problem it´s with my stream server latency, and not with my unity project.
But still... there is a way to persist the video to play with high latency?

How to remove Objects from PDF File using PDFClown

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.
So far I am trying to do this with a ContentScanner:
public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);
private int count = 0;
public void scan(ContentScanner level) {
if (level == null)
return;
while (level.moveNext()) {
ContentObject object = level.getCurrent();
if (object instanceof ContainerObject) {
// Scan the inner level!
scan(level.getChildLevel());
} else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
AffineTransform ctm = level.getState().getCtm();
Color<?> strokeColor = level.getState().getStrokeColor();
Color<?> fillColor = level.getState().getFillColor();
if (checkWhite(fillColor) && checkWhite(strokeColor)) {
level.remove();
} else {
LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
}
} else {
LOG.info("Object:" + object);
}
}
}
It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):
Document targetDoc = new File().getDocument();
targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
Page page = targetDoc.getPages().get(0);
Contents contents = page.getContents();
FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
filterWhitePathScanner.scan(new ContentScanner(contents));
LOG.info("White Paths: " + filterWhitePathScanner.getCount());
targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);
The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?
Thanks,
Thomas
Finally found the solution in the Java doc:
You have to call contents.flush(); to persist the changes into the pdf file.
So I added this line to the PDF handling code before calling save and it works!

QHttpMultiPart generates different boundary

When I try to upload files by QHttpMultiPart, there appears a problem. I use the CommonsMultipartResolver.isMultipart() to validate the request, and it returns false.
So I capture frame by Wireshark, and I found an interesting thing: the boundaries in the frame are all different.
Here is my client code
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart zipPart;
zipPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/zip"));
zipPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\""));
QFile *file = new QFile(pakPath);
file->open(QIODevice::ReadOnly);
zipPart.setBodyDevice(file);
multiPart->append(zipPart);
QNetworkRequest *request = new QNetworkRequest(QUrl(url));
manager->put(*request, multiPart);
And the server code
CommonsMultipartResolver(request.getSession().getServletContext());
if( multipartResolver.isMultipart(request) ) { // here return false
...
I have two questions:
Q1: Is the different boundary make itself be an abnormal in CommonsMultipartResolver?
Q2: Is Different boundary normal or Qt make mistake?
I have a same problem too , my boundary supposed whitout "" ,
I find the source code about QHttpMultiPart class , I found that qt has force set "" by hand . so whatever we set , it will always with "".
qt QHttpMultiPart source code
<pre><code>QNetworkRequest QNetworkAccessManagerPrivate::prepareMultipart(const QNetworkRequest &request, QHttpMultiPart *multiPart)
{
// copy the request, we probably need to add some headers
QNetworkRequest newRequest(request);
// add Content-Type header if not there already
if (!request.header(QNetworkRequest::ContentTypeHeader).isValid()) {
QByteArray contentType;
contentType.reserve(34 + multiPart->d_func()->boundary.count());
contentType += "multipart/";
switch (multiPart->d_func()->contentType) {
case QHttpMultiPart::RelatedType:
contentType += "related";
break;
case QHttpMultiPart::FormDataType:
contentType += "form-data";
break;
case QHttpMultiPart::AlternativeType:
contentType += "alternative";
break;
default:
contentType += "mixed";
break;
}
// putting the boundary into quotes, recommended in RFC 2046 section 5.1.1
contentType += "; boundary=\"" + multiPart->d_func()->boundary + '"';
newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));
}
// add MIME-Version header if not there already (we must include the header
// if the message conforms to RFC 2045, see section 4 of that RFC)
QByteArray mimeHeader("MIME-Version");
if (!request.hasRawHeader(mimeHeader))
newRequest.setRawHeader(mimeHeader, QByteArray("1.0"));
QIODevice *device = multiPart->d_func()->device;
if (!device->isReadable()) {
if (!device->isOpen()) {
if (!device->open(QIODevice::ReadOnly))
qWarning("could not open device for reading");
} else {
qWarning("device is not readable");
}
}
return newRequest;
}
</code></pre>
I tried to inherit QHttpMultiPart and rewrite the QNetworkAccessManagerPrivate::prepareMultipart(const QNetworkRequest &request, QHttpMultiPart *multiPart) function , but it seems too bother to do.
finally , I found a simple way to solve that , it just need to reset boundary paramter agian , that before you post data. it worked. here is my code
<pre><code>
void PeddingBizUI::ossUploadPicture_post(PolicyInfo policy, QString pathName)
{
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart keyPart;
QString fileName = getFileNameFromPath(pathName);
keyPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-
data; name=\"key\""));
QByteArray ba = QByteArray(QString(policy.dir +
fileName).toStdString().data());
qDebug()<<ba;
keyPart.setBody(ba);
QHttpPart policyPart;
policyPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"policy\""));
policyPart.setBody(policy.policy.toStdString().data());
QHttpPart SignaturePart;
SignaturePart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"Signature\""));
SignaturePart.setBody(policy.signature.toStdString().data());
QHttpPart OSSAccessKeyIdPart;
OSSAccessKeyIdPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"OSSAccessKeyId\""));
OSSAccessKeyIdPart.setBody(policy.accessId.toStdString().data());
QHttpPart success_action_statusPart;
success_action_statusPart.setHeader(QNetworkRequest::ContentDispositionHeader,
QVariant("form-data; name=\"success_action_status\""));
success_action_statusPart.setBody(QByteArray::number(200));
QHttpPart aclPart;
aclPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-
data; name=\"x-oss-object-acl\""));
aclPart.setBody("public-read");
QHttpPart imagePart;
QString str = QString("form-data; name=\"file\";
filename=\"%1\"").arg(fileName);
qDebug()<<fileName;
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(str));
//不可调换header的先后顺序否则导致
imagePart.setHeader(QNetworkRequest::ContentTypeHeader,
QVariant("image/jpeg")); //请求失败, 提示body data not well formed 失
败
QFile *fileOpen = new QFile(pathName);
fileOpen->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(fileOpen);
fileOpen->setParent(multiPart); // we cannot delete the file now, so delete it
with the multiPart
multiPart->append(keyPart);
multiPart->append(policyPart);
multiPart->append(SignaturePart);
multiPart->append(OSSAccessKeyIdPart);
multiPart->append(success_action_statusPart);
//multiPart->append(aclPart);
multiPart->append(imagePart);
quint32 random[6];
QRandomGenerator::global()->fillRange(random);
QByteArray boundary = "--boundary_zyl_"
+ QByteArray::fromRawData(reinterpret_cast<char *>(random),
sizeof(random)).toBase64();
QUrl url(policy.host);
// QUrl url("http://arithmetic-oss.oss-cn-shenzhen.aliyuncs.com");
QNetworkRequest request(url);
QByteArray contentType;
contentType += "multipart/";
contentType += "form-data";
contentType += "; boundary=";
contentType += boundary;
multiPart->setBoundary(boundary);
request.setHeader(QNetworkRequest::ContentTypeHeader, contentType);
QNetworkReply *reply = m_netUtils.m_manager->post(request, multiPart);
connect(reply, &QNetworkReply::finished, this, [this, multiPart](){
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
qDebug()<<"ossUploadPicture_post response";
onOssUploadPictureResponse(reply);
multiPart->setParent(reply); //内存泄露
reply->deleteLater();
});
// delete the multiPart with the reply
}</code></pre>
and then problem solved.

Why does live camera capture control with Xamarin Forms on iOS freeze?

I downloaded the source for Xamarin Moments from GitHub and now I'm trying to convert the CameraPage renderer from Page to a ContentView
Then I refactored the code to make it a ContentView renderer. Most of the actual setup of the live preview and image capture comes from the Moments app with some refactoring where needed/preferred.
The live preview shows up but when I press the button to take the picture the app freezes without an exception, not even in Xcode's console view.
//this is how it's called:
btnTakePicture.Clicked += (s,e)=> { GetCameraImage().Wait(); };
// this method freezes
public async Task<byte[]> GetCameraImage()
{
byte[] imageBuffer = null;
if (captureDeviceInput != null)
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
Console.WriteLine("[HASFIQWRPPOA] This message shows up");
// this is where the app freezes, even though the live preview still moves.
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
Console.WriteLine("[CLKJFADSFQXW] THIS DOESN'T SHOW UP");
// var jpegImageAsBytes = AVCaptureStillImageOutput.JpegStillToNSData (sampleBuffer).ToArray ();
var jpegImageAsNsData = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer);
Console.WriteLine("[ROIAJDGNQWTG]");
// var image = new UIImage (jpegImageAsNsData);
// var image2 = new UIImage (image.CGImage, image.CurrentScale, UIImageOrientation.UpMirrored);
// var data = image2.AsJPEG ().ToArray ();
imageBuffer = jpegImageAsNsData.ToArray();
Console.WriteLine("[FIOUJGAIDGUQ] Image buffer: "+imageBuffer.Length);
}
if (imageBuffer != null && imageBuffer.Length > 100)
{
using (var ms = new MemoryStream(imageBuffer))
{
var uiimg = UIImage.LoadFromData(NSData.FromStream(ms));
this.Add(new UIImageView(uiimg));
}
}
return imageBuffer;
}
Here is how I set the live preview
// This method runs fine and the camera preview is started as expected
public void SetupLiveCameraStream()
{
try
{
// add a UIView to the renderer
liveCameraStream = new UIView()
{
Frame = new CGRect(0f, 0f, Element.Width, Element.Height),
};
this.Add(liveCameraStream);
// find a camera
var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
if (captureDevice != null)
{
Console.WriteLine("[ZKSDJGWEHSY] Capture device found"); // not the case on simulator
captureSession = new AVCaptureSession();
videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
{
Frame = liveCameraStream.Bounds
};
liveCameraStream.Layer.AddSublayer(videoPreviewLayer);
ConfigureCameraForDevice(captureDevice);
captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);
var dictionary = new NSMutableDictionary();
dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
stillImageOutput = new AVCaptureStillImageOutput()
{
OutputSettings = new NSDictionary()
};
captureSession.AddInput(captureDeviceInput);
captureSession.AddOutput(stillImageOutput);
captureSession.StartRunning();
Console.WriteLine("[OIGAJGUWRJHWY] Camera session started");
}
else
{
Console.WriteLine("[OASDFUJGOR] Could not find a camera device");
}
}
catch (Exception x)
{
Console.WriteLine("[QWKRIFQEAHJF] ERROR:" + x);
}
}
I had this issue, and it turned out I was deadlocking because of a combination of using async/await with Task.Result. At a guess you could be experiencing something similar with your usage of Task.Wait().
The two sections of code:
btnTakePicture.Clicked += await (s,e) => { GetCameraImage().Wait(); };
And:
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);

Android crop intent doesn't work on system gallery app but works on 3rd-party app

I try to pick an image from sdcard and then crop it.
ACTION_PICK is OK, but when i call ACTION_CROP, my system gallery app (I call it as A) can't done the action, but another app (B) can.
I tried the following cases:
1/ Pick by A and then crop by A => pick OK, crop fail
2/ Pick by B and then crop by A => the same as first case.
3/ Pick by A and then crop by B => every things OK.
4/ Pick by B and then crop by B => every things OK.
So my temporary conclusion is: my system app can't do the crop action with my code (may be i forgot something). Here is my code:
ACTION_PICK:
public Intent galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
galleryIntent.putExtra("return-data", true);
return galleryIntent;
}
ACTION_CROP:
public Intent cropIntent(Uri inUri, int outputX, int outputY,
boolean isScale) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(inUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", outputX);
cropIntent.putExtra("aspectY", outputY);
cropIntent.putExtra("outputX", outputX);
cropIntent.putExtra("outputY", outputY);
cropIntent.putExtra("scale", isScale);
cropIntent.putExtra("return-data", true);
return cropIntent;
}
My onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_GALLERY:
imageUri = data.getData();
startActivityForResult(cropIntent(imageUri,
500, 500, true), REQUEST_CODE_CROP);
break;
case REQUEST_CODE_CROP:
Bundle extras = data.getExtras();
Bitmap tempBitmap = extras.getParcelable("data");
imgvMain.setImageBitmap(null);
imgvMain.setImageBitmap(tempBitmap);
break;
}
} else {
imageUri = null;
}
}
Am i missing somethings?
Thank for your attention!
I use this code successfully for Android 2.2 and up:
It opens a selection of apps that can get image files e.g. the Gallery app. If the selected app can crop, it will also do so.
The cropped image will be saved to the supplied temp file.
(note the small difference for KITKAT).
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("outputX", Constants.IMAGE_WIDTH);
intent.putExtra("outputY", Constants.IMAGE_HEIGHT);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(<a temp file created somewhere>));
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
{
intent.setAction(Intent.ACTION_GET_CONTENT);
}
else
{
intent.setAction(Intent.ACTION_PICK);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(intent, RESULT_CROP);
EDIT:
I ended up using custom cropping using: https://github.com/biokys/cropimage. It was very easy and I had no more troubles with cropping :-)
I checked the logs by filtering with gallery3d and found out that the stock app is not getting permission to access the uri. Hence it's behaving unexpectedly. That behaviour is different for different platforms.
Solution:
get the uri of the selected image in onActivityResult() for intent ACTION_PICK.
save the image temporarily.
create new URI from the saved image.
pass the new URI to com.android.camera.action.CROP.
Sample code: (Dont copy paste. for simplicity ,I have removed the error checks and async tasks.)
public void pickCroppedPhoto(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
populateCropExtras(activity, photoPickerIntent);
startActivityForResult(photoPickerIntent , REQUEST_CODE_PICK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_PICK ) {
File mainImage = saveUriInFile( this,
data.getData(),
getTempFileForMainImage());
if (null == mainImage) {
handleImageSelectionFailure();
}else {
try {
Uri mainFileUri = Uri.fromFile(mainImage);
performCrop(this,mainFileUri);
}catch(Exception e){
handleImageSelectionFailure();
}
}
}else if ( requestCode == PIC_CROP ){
postImageSelection(data.getData());
}
}
Here is my performCrop code which is similar to that of the question.
public static boolean performCrop(Activity activity, Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
if (populateCropExtras(activity, cropIntent)) return false;
activity.startActivityForResult(cropIntent, PIC_CROP);
return true;
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
String errorMessage = "Device doesn't support crop!";
Log.w(PhotoPickerUtil.class.getCanonicalName(), errorMessage);
return false;
}catch (IOException ioe){
String errorMessage = "Error while getting temporary file from external storage";
Log.w(PhotoPickerUtil.class.getCanonicalName(), errorMessage);
return false;
}
}
private static void populateCropExtras(Activity activity, Intent cropIntent) throws IOException { {
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate output X and Y
cropIntent.putExtra("outputX", 300);
cropIntent.putExtra("outputY", 300);
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
Uri tempUri = Uri.fromFile(getTempFile(activity));
cropIntent.putExtra("output", tempUri);
}

Resources