symba (779893), страница 40

Файл №779893 symba (Symbian Books) 40 страницаsymba (779893) страница 402018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 40)

Using the input file// name may lead to undesired side effects and file corruption,// so generate another.TFileName destFileName(aFileName);destFileName.Append(_L(".transformed"));iImgTransform->SetDestFilenameL(destFileName);if (aNewMainImageSize == NULL) // we do not need to re-size// the main image{// tell the framework not to resize the main imageiImgTransform->SetPreserveImageData(ETrue);// but we must still call this method with any size parameteriImgTransform->SetDestSizeInPixelsL(TSize(1,1));}else{// Allow the framework to resize the main imageiImgTransform->SetPreserveImageData(EFalse);// set the new main image sizeiImgTransform->SetDestSizeInPixelsL(*aNewMainImageSize);}TRANSFORMING IMAGES187// Pass the defined options.

Note that it is not possible to specify the// thumbnail size, if a thumbnail is to be added.iImgTransform->SetOptionsL(aTransformOpt);// Tell the framework that all the options are set nowiImgTransform->SetupL();// Obtain extensionCImageTransformPluginExtension* ext = iImgTransform->Extension();// If extension is present and it is of desired typeif (ext != NULL && ext->Uid().iUid == KUidTransformJpegExtension){// It can be cast to the CJPEGExifTransformExtension, so// we can gain access to the MExifMetadata interfaceMExifMetadata* exifAccessor =static_cast <CJPEGExifTransformExtension*>(ext)->ExifMetadata();// Create an instance of the EXIF reader helperTExifReaderUtility exifReader(exifAccessor);// Create an instance of the EXIF writer helperTExifWriterUtility exifWriter(exifAccessor);HBufC8* imageDescription = NULL;// Check if the image has a description tagif (KErrNotFound == exifReader.GetImageDescription(imageDescription)){// Create and set our own image description_LIT8(KImageDescription, "Image Transformed!");imageDescription = KImageDescription().AllocLC();User::LeaveIfError(exifWriter.SetImageDescription(imageDescription));CleanupStack::PopAndDestroy(imageDescription);}else{// description is already there, so deallocate it.delete imageDescription;}}// tell the framework to start the image transformationiImgTransform->Transform(iStatus);// tell the active scheduler there is an outstanding requestSetActive();}The parameters passed to the BeginTransformL() method are:• const TDesC&aFileName is an input file name, no more than that.• CImageTransform::TOptions aTransformOpt can be anycombination of supported transformation options, used in the sameway as CImageTransform::SetOptions().• const TSize* aNewMainImageSize is the (optional) destinationimage size.

A caller may specify NULL, in which case no imagere-sizing occurs.188IMAGE CONVERSION LIBRARYThe BeginTransformL() method can do almost anything that theAPI defines. The basic scenario of CImageTransform usage is asfollows:1.Create an instance of CImageTransform.2.Perform mandatory setup: image source, destination and the destination image size. Note that the destination size setup call is mandatoryand must always be made even if the image is not going to bere-sized, in which case any size can be specified.3.Call CImageTransform::SetupL(). At this point the frameworktries to load a plug-in. If no suitable plug-in is found, a leave occurs.4.Perform additional optional setup via non-standard extensions.

Unlikewith the CImageDecoder API, these extensions are interface-basedrather than data-based (see Figure 6.11 for an example of an extension).5.Once all the setup is done, start the asynchronous transformationprocess by calling CImageTransform::Transform().6.Handle the transformation result.7.If more images need to be transformed, re-use the framework objectby calling CImageTransform::Reset().The framework enforces the call sequence by panicking applicationswhich do not adhere to the required sequence of calls.CImageTransformPluginExtension+Defines base interfacefor all the extensionsUid() : const TUidDefines a plug-in-specific set ofextended methodsCJPEGExifTransformExtensiondefines just one additionalmethodCImageTransform+Extension() :CJPEGExifTransformExtensionCImageTransformPluginExtension∗Figure 6.11+ExifMetadata() : MExifMetadata∗CImageTransform extension class diagramNATIVE BITMAP OPERATIONS189CImageTransform::TOptions is a mix of framework operationinstructions and output image options.

If the input image has a thumbnail but CImageTransform::EThumbnail is not given to CImageTransform::SetOptionsL(), then the thumbnail is removed andthe output image does not have a thumbnail.6.5.2 Limitations of CImageTransformAt the time of writing, the only plug-in supplied by Symbian is a JPEGExif-enabled plug-in. No other plug-ins are available from phone manufacturers, which means that use of CImageTransform is limited to JPEGformat image re-sizing, thumbnail addition or removal and Exif metadataaddition or editing.A limitation of the existing JPEG plug-in implementation is that it isnot possible to fine-tune JPEG compression parameters (quality factor,quantization tables, etc.) in the same way as is possible when encodinga bitmap using the CImageEncoder API.6.6 Native Bitmap OperationsThe main purpose of this API is to provide support for the two mostcommon bitmap transformations: scaling and rotation.

It is fairly straightforward to use this API, which is based on plug-ins. Symbian suppliesdefault software-based plug-in implementations, which can be replacedby a device manufacturer with hardware-accelerated implementations.These APIs can be very helpful for applications that view images, incases where an image decoder cannot satisfy an application’s requestedoutput image size (see Section 6.2.4) or bitmap rotation is needed.The API consists of two classes: CBitmapScaler and CBitmapRotator, which can perform scaling and rotation (in multiples of 90degrees), respectively.

These classes share the same basic usage pattern:1. An instance of the class is created using the synchronous factorymethod, NewL().2. Optional synchronous setup methods (only for CBitmapScaler atthe moment) are called.3. The asynchronous transformation operation is invoked.The Symbian-supplied implementations allow object instance re-useonce the asynchronous operation has been completed: it is possible touse the same instance of a scaler to perform scaling of several bitmaps(but not simultaneously).190IMAGE CONVERSION LIBRARYBoth classes support two modes of operation – a bitmap can be transformed either ‘in-place’ or using a separate bitmap as the destination.The latter case is interesting as it allows the bitmap color mode to beconverted as well.

For example, it is possible to ask a bitmap of colormode EColor64K to be scaled or rotated and the result converted intothe destination bitmap color mode.6.6.1 Scaling BitmapsThe following code demonstrates the basic use of the scaling API. It makesuse of the single-bitmap variant of the API, specifies the destination sizeand asks the scaler to preserve the aspect ratio of the image:void CSimpleBitmapScalerHandler::ConstructL(){iScaler = CBitmapScaler::NewL();CActiveScheduler::Add(this); // Add to scheduler}CSimpleBitmapScalerHandler::∼CSimpleBitmapScalerHandler(){// Cancel any request, if outstandingCancel();// Delete instance variables, if anydelete iScaler;}void CSimpleBitmapScalerHandler::BeginScalingL(CFbsBitmap& aSource,const TSize& aDestSize,CBitmapScaler::TQualityAlgorithm aQuality){// We are not checking the error code of this operation as// there is nothing we can do about itiScaler->DisablePostProcessing(ETrue);User::LeaveIfError( iScaler->SetQualityAlgorithm(aQuality) );// start scaling with aspect ratio preservationiScaler->Scale(&iStatus, aSource, aDestSize, ETrue);// Tell scheduler a request is activeSetActive();}void CSimpleBitmapScalerHandler::RunL(){if (iStatus.Int() == KErrNone){// do something with scaled bitmap}else{//handle error}}The benefits of the single-bitmap scaling method are as follows:• The application does not have to create a destination bitmap anddiscard the source (if it is no longer needed).

You should useNATIVE BITMAP OPERATIONS191the two-bitmap API variant if you need to preserve the originalbitmap.• The application does not have to bother about the exact destinationsize. Scaling with aspect ratio preservation is probably the most common use case, but it is quite tricky. Let us imagine that an applicationneeds to enlarge an image of size (20, 30) so it fits into a rectangleof size (43, 62).

What is the output size in this case? It depends onthe scaling algorithm implementation. We are dealing with a plug-inbased API which can have slightly different implementation-specificbehavior. Where we’re dealing with a single-bitmap API method, welet the plug-in do the hard work.• This method should consume less memory than the two-bitmap one.Depending on the use case (either enlarging or downscaling theimage), however, memory consumption can be the same as thetwo-bitmap API.The benefits of the two-bitmap variant are as follows:• An API client can potentially combine scaling with color depthtransformation10 as the input and output bitmaps may be of differentcolor modes.• The original image is preserved.If the two-bitmap scaling method is used with the aspect ratio preservation parameter set to ‘true’, then the default scaler implementationdoes its best to fit the result into the destination bitmap provided.

Insome cases, this may cause ‘borders’ to appear on the final image, if theapplication uses a destination size calculation logic which is differentto that employed by the scaling plug-in. The best way of avoiding thisproblem is to use a single-bitmap scaling method.The CBitmapScaler class has some optional setup methods whichcan be used to tune scaling behavior (see Table 6.8).6.6.2 Performance Hints for ScalingPerformance of the default software implementation of the scaling plugin can be quite sensitive to the input parameters.

The two main factorswhich affect scaling performance are:• source and destination bitmap color modes• scaling algorithm quality.10 Color depth transformation can be quite costly in terms of both memory and CPUpower consumption (especially when color dithering is enabled).192Table 6.8IMAGE CONVERSION LIBRARYTuning Options for ScalingMethodDescriptionUseLowMemoryAlgorithm()Instructs the scaler to use as little memory as possible.With the Symbian-provided reference implementation,you can gain some performance. It may be worthalways using this option.DisablePostProcessing()Disables color dithering during color depth adjustments.

Disabling color dithering, in most cases, provides a significant performance increase.SetQualityAlgorithm()Allows changing of the scaling quality. As usual, thequality of image processing comes at the price ofperformance and memory consumption. The defaultscaler implementation supports the following qualitylevels:• EMinimumQuality causes the scaler to use the‘nearest neighbor’ algorithm.• EMediumQuality causes a simple weight-basedinterpolation to be applied in the horizontal dimension.• EMaximumQuality causes interpolation to beused for both vertical and horizontal dimensions.If no quality setting method is called, then EMaximumQuality is used by default.Note: Plug-ins provided by Symbian OS interpret theparameters in this way, but other plug-ins may behavedifferently.The first thing to consider while looking at performance is to make theapplication use the same color mode for both the source and destinationbitmaps, thus avoiding pixel translations.The scaler provided by Symbian OS is optimized to perform fairlyfast pixel operations for bitmaps in which the color mode has eightbits per color channel.

Характеристики

Тип файла
PDF-файл
Размер
1,13 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6384
Авторов
на СтудИзбе
308
Средний доход
с одного платного файла
Обучение Подробнее